ai-helper-agent 2.8.11 → 2.8.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{chat-export-DIK7kXq9.js → chat-export-DZntnUPd.js} +4 -4
- package/dist/assets/content.js +88 -81
- package/dist/assets/{context-indicator-CHdsVqH3.js → context-indicator-BSGa1g7l.js} +228 -228
- package/dist/assets/options.js +8 -8
- package/dist/assets/side_panel.js +141 -141
- package/dist/assets/version-Dc9zhEVX.js +172 -0
- package/dist/assets/voice-shortcut-Dx863RGz.js +3 -0
- package/dist/manifest.json +2 -3
- package/dist/options.html +2 -2
- package/dist/side_panel.html +4 -4
- package/package.json +1 -1
- package/dist/assets/version-kRemUQxx.js +0 -174
- package/dist/assets/voice-shortcut-Dtt3nhkz.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agent-store-CE4-QMOA.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-CqsAD3Fd.js","assets/i18n-DvmxOw8q.js","assets/pdf-DnVqBaAN.js","assets/__vite-browser-external-CM3Eme-n.js","assets/lib-YwkWjNcC.js","assets/jszip.min-DO6SOhXU.js","assets/dist-DuuG_8Br.js","assets/chat-export-
|
|
2
|
-
import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as a}from"./i18n-DvmxOw8q.js";import{$ as o,At as s,Dt as c,Et as l,H as u,Ht as d,Jt as f,Lt as p,Ot as m,Pt as h,Rt as g,S as _,St as v,U as y,Ut as b,Y as x,Yt as S,b as C,ct as w,dt as T,kt as E,lt as D,ut as O,wt as k,x as A}from"./model-profiles-CqsAD3Fd.js";import{A as j,B as M,C as N,D as ee,E as te,M as ne,O as re,S as ie,T as ae,a as oe,b as se,c as ce,d as le,f as ue,h as de,j as fe,k as pe,l as me,m as he,n as ge,o as _e,p as ve,r as ye,s as be,t as xe,u as Se,v as Ce,w as we,x as Te,y as Ee}from"./session-store-DfBABQNR.js";import{a as De,n as Oe,
|
|
3
|
-
...[历史摘要已截断]`:e)}return{messages:[...g,o],keptHistory:g,compactionApplied:l,trimmedCount:y,historySummaryText:v}}function rn(e,t){return!t||!t.summary?e:`${e}\n\n${r(`contextUsage.compactionInjection`,{count:t.compressedCount||0})}\n${t.summary}`}function an(e,t,n,r){return t?.compactionApplied&&n?.summary?e[0]={...e[0],content:rn(e[0].content,n)}:n?.summary&&r?.warn(`[SidePanel] contextCompaction invalid (upToMessageId not found), ignored this send`),e}function on({model:e,customModelMap:t=null,systemPromptText:n=``,toolCount:r=0,history:i=[],inputText:a=``,maxMemoryMessages:o=null,compaction:u=null,isolateChat:d=!0,userConfiguredWindow:f=0}={}){let m=p(e,f,t),h=m-s(n)-l-$t,g=Math.floor(Math.max(h,0)*en),_={role:`user`,content:a},v=d?u:null,y=nn(i,{isolateChat:d,maxMemoryMessages:o,compaction:v,historyBudget:g,currentMessage:_}),b=s(y.compactionApplied?rn(n,v):n),x=r*200,S=E(y.keptHistory),C=a&&a.trim()?E([_]):0,w=b+x+S+C,T=c(w,m);return{usedTokens:w,contextWindow:m,ratio:m>0?w/m:0,level:T.level,breakdown:{system:b,tools:x,history:S,input:C,outputReserve:l,safetyMargin:$t,selectedCount:y.keptHistory.length,totalCount:i.length,trimmedCount:y.trimmedCount,compactionApplied:y.compactionApplied,compactionInvalid:!!(v&&v.summary&&!y.compactionApplied),historyBudget:g}}}function sn(e,{maxMemoryMessages:t=null,compaction:n=null}={}){let r=nn(e,{isolateChat:!0,maxMemoryMessages:t,compaction:n,historyBudget:1/0,currentMessage:null}),i=[],a=!!(r.compactionApplied&&n?.summary);a&&i.push({role:`user`,content:`【已有摘要】\n${n.summary}`});for(let e of r.keptHistory){let t=d(e.content);i.push({role:e.role,content:typeof t==`string`?t:JSON.stringify(t??``)||``})}return{material:i,includedCount:r.keptHistory.length,hasOldSummary:a}}function cn(e){if(!e||!e.trim()||e.trim()==`/`)return;let t=e.trim(),n=C.inputHistory.indexOf(t);n!==-1&&C.inputHistory.splice(n,1),C.inputHistory.push(t),C.inputHistory.length>20&&C.inputHistory.shift(),ln()}function ln(){try{chrome.storage.local.set({inputHistory:C.inputHistory}),i.debug(`[SidePanel] input history saved,count:`,C.inputHistory.length)}catch(e){i.error(`[SidePanel] saveinput history failed:`,e)}}var un=[`workspace`,`bookmark`,`toc`,`search`,`todo`,`schedule`],dn=`.workspace-panel.expanded, .bookmark-panel.expanded, .message-toc-panel.expanded, .search-panel.expanded, .schedule-panel.open`,fn=null,pn=null;function mn(){if(fn)return fn;fn=document.createElement(`div`),fn.className=`side-rail`,fn.id=`sideRail`,fn.innerHTML=un.map(e=>`<div class="side-rail-slot" data-slot="${e}"></div>`).join(``),document.body.appendChild(fn),gn();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(gn).observe(e),window.addEventListener(`resize`,gn),fn}function hn(e){return(fn||mn()).querySelector(`.side-rail-slot[data-slot="${e}"]`)}function gn(){if(!fn)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect(),n=window.innerHeight;fn.style.top=`${Math.max(0,Math.round(t.top))}px`,fn.style.bottom=`${Math.max(0,Math.round(n-t.bottom))}px`,_n()}function _n(){pn&&clearTimeout(pn),pn=setTimeout(()=>{pn=null,document.querySelectorAll(dn).forEach(
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agent-store-CE4-QMOA.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-CqsAD3Fd.js","assets/i18n-DvmxOw8q.js","assets/pdf-DnVqBaAN.js","assets/__vite-browser-external-CM3Eme-n.js","assets/lib-YwkWjNcC.js","assets/jszip.min-DO6SOhXU.js","assets/dist-DuuG_8Br.js","assets/chat-export-DZntnUPd.js","assets/dist-BUuoW_84.js","assets/version-Dc9zhEVX.js","assets/voice-shortcut-Dx863RGz.js","assets/session-store-DfBABQNR.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as a}from"./i18n-DvmxOw8q.js";import{$ as o,At as s,Dt as c,Et as l,H as u,Ht as d,Jt as f,Lt as p,Ot as m,Pt as h,Rt as g,S as _,St as v,U as y,Ut as b,Y as x,Yt as S,b as C,ct as w,dt as T,kt as E,lt as D,ut as O,wt as k,x as A}from"./model-profiles-CqsAD3Fd.js";import{A as j,B as M,C as N,D as ee,E as te,M as ne,O as re,S as ie,T as ae,a as oe,b as se,c as ce,d as le,f as ue,h as de,j as fe,k as pe,l as me,m as he,n as ge,o as _e,p as ve,r as ye,s as be,t as xe,u as Se,v as Ce,w as we,x as Te,y as Ee}from"./session-store-DfBABQNR.js";import{a as De,n as Oe,o as ke,r as Ae,t as je}from"./voice-shortcut-Dx863RGz.js";import{A as Me,B as Ne,C as Pe,D as Fe,F as Ie,G as Le,H as Re,I as ze,J as P,L as Be,O as Ve,P as He,R as F,S as Ue,T as We,U as Ge,V as Ke,X as qe,Y as Je,_ as Ye,b as Xe,d as Ze,f as Qe,g as $e,h as et,i as tt,j as I,k as nt,l as rt,m as it,n as at,p as ot,u as st,v as ct,w as lt,x as ut,z as dt}from"./version-Dc9zhEVX.js";import{a as ft,c as pt,i as mt,n as ht,o as gt,r as _t,s as vt}from"./agent-store-CE4-QMOA.js";import{A as yt,C as bt,D as xt,E as St,M as Ct,O as wt,S as Tt,T as Et,_ as Dt,a as Ot,b as kt,c as At,d as jt,f as Mt,g as Nt,h as Pt,i as Ft,k as It,l as Lt,m as Rt,n as zt,o as Bt,p as Vt,r as Ht,s as Ut,t as Wt,u as Gt,v as Kt,w as qt,x as Jt,y as Yt}from"./workspace-manager-D6xww21F.js";var Xt=ne.map(e=>e.id),Zt=[...new Set([...S,`mcp`,`knowledge`])],Qt=[{labelKey:`presetMode.preciseLabel`,tipKey:`presetMode.preciseTip`,temp:.2,topP:1},{labelKey:`presetMode.generalLabel`,tipKey:`presetMode.generalTip`,temp:.45,topP:.9},{labelKey:`presetMode.divergentLabel`,tipKey:`presetMode.divergentTip`,temp:.65,topP:.9},{labelKey:`presetMode.creativeLabel`,tipKey:`presetMode.creativeTip`,temp:.9,topP:.9}];n(`zh`,{contextUsage:{compactionInjection:`[上下文摘要|压缩了{count}条历史]`}}),n(`en`,{contextUsage:{compactionInjection:`[Context Summary | {count} messages compacted]`}});var $t=2e3,en=.7,tn=1e3;function nn(e,{isolateChat:t=!0,maxMemoryMessages:n=null,compaction:r=null,historyBudget:i=1/0,currentMessage:a=null}={}){let o=a||{role:`user`,content:``};if(!t)return{messages:[o],keptHistory:[],compactionApplied:!1,trimmedCount:0,historySummaryText:null};let c=Array.isArray(e)?e:[],l=!1,u=-1;r&&r.summary&&r.upToMessageId&&(u=c.findIndex(e=>e.messageId===r.upToMessageId),l=u>=0);let f=c,p=c.map((e,t)=>t);n&&n>0&&c.length>n&&(f=c.slice(c.length-n),p=p.slice(c.length-n));let m=[];for(let e=0;e<f.length;e++)l&&p[e]<=u||m.push(f[e]);let g=[],_=E([o]);for(let e=m.length-1;e>=0;e--){let t=m[e],n=E([{...t,content:d(t.content)}]);if(_+n<=i)g.unshift(t),_+=n;else break}let v=null,y=m.length-g.length;if(y>0){let e=h(m.slice(0,y));e&&(v=s(e)>tn?e.substring(0,tn*4)+`
|
|
3
|
+
...[历史摘要已截断]`:e)}return{messages:[...g,o],keptHistory:g,compactionApplied:l,trimmedCount:y,historySummaryText:v}}function rn(e,t){return!t||!t.summary?e:`${e}\n\n${r(`contextUsage.compactionInjection`,{count:t.compressedCount||0})}\n${t.summary}`}function an(e,t,n,r){return t?.compactionApplied&&n?.summary?e[0]={...e[0],content:rn(e[0].content,n)}:n?.summary&&r?.warn(`[SidePanel] contextCompaction invalid (upToMessageId not found), ignored this send`),e}function on({model:e,customModelMap:t=null,systemPromptText:n=``,toolCount:r=0,history:i=[],inputText:a=``,maxMemoryMessages:o=null,compaction:u=null,isolateChat:d=!0,userConfiguredWindow:f=0}={}){let m=p(e,f,t),h=m-s(n)-l-$t,g=Math.floor(Math.max(h,0)*en),_={role:`user`,content:a},v=d?u:null,y=nn(i,{isolateChat:d,maxMemoryMessages:o,compaction:v,historyBudget:g,currentMessage:_}),b=s(y.compactionApplied?rn(n,v):n),x=r*200,S=E(y.keptHistory),C=a&&a.trim()?E([_]):0,w=b+x+S+C,T=c(w,m);return{usedTokens:w,contextWindow:m,ratio:m>0?w/m:0,level:T.level,breakdown:{system:b,tools:x,history:S,input:C,outputReserve:l,safetyMargin:$t,selectedCount:y.keptHistory.length,totalCount:i.length,trimmedCount:y.trimmedCount,compactionApplied:y.compactionApplied,compactionInvalid:!!(v&&v.summary&&!y.compactionApplied),historyBudget:g}}}function sn(e,{maxMemoryMessages:t=null,compaction:n=null}={}){let r=nn(e,{isolateChat:!0,maxMemoryMessages:t,compaction:n,historyBudget:1/0,currentMessage:null}),i=[],a=!!(r.compactionApplied&&n?.summary);a&&i.push({role:`user`,content:`【已有摘要】\n${n.summary}`});for(let e of r.keptHistory){let t=d(e.content);i.push({role:e.role,content:typeof t==`string`?t:JSON.stringify(t??``)||``})}return{material:i,includedCount:r.keptHistory.length,hasOldSummary:a}}function cn(e){if(!e||!e.trim()||e.trim()==`/`)return;let t=e.trim(),n=C.inputHistory.indexOf(t);n!==-1&&C.inputHistory.splice(n,1),C.inputHistory.push(t),C.inputHistory.length>20&&C.inputHistory.shift(),ln()}function ln(){try{chrome.storage.local.set({inputHistory:C.inputHistory}),i.debug(`[SidePanel] input history saved,count:`,C.inputHistory.length)}catch(e){i.error(`[SidePanel] saveinput history failed:`,e)}}var un=[`workspace`,`bookmark`,`toc`,`search`,`todo`,`schedule`],dn=`.workspace-panel.expanded, .bookmark-panel.expanded, .message-toc-panel.expanded, .search-panel.expanded, .schedule-panel.open`,fn=null,pn=null;function mn(){if(fn)return fn;fn=document.createElement(`div`),fn.className=`side-rail`,fn.id=`sideRail`,fn.innerHTML=un.map(e=>`<div class="side-rail-slot" data-slot="${e}"></div>`).join(``),document.body.appendChild(fn),gn();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(gn).observe(e),window.addEventListener(`resize`,gn),fn}function hn(e){return(fn||mn()).querySelector(`.side-rail-slot[data-slot="${e}"]`)}function gn(){if(!fn)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect(),n=window.innerHeight;fn.style.top=`${Math.max(0,Math.round(t.top))}px`,fn.style.bottom=`${Math.max(0,Math.round(n-t.bottom))}px`,_n()}function _n(){pn&&clearTimeout(pn),pn=setTimeout(()=>{pn=null,document.querySelectorAll(dn).forEach(Fe)},120)}n(`zh`,{messageToc:{toggleTitle:`显示目录(H{count}个标题)`,title:`目录`,headingCount:`{count} 个`,lock:`锁定目录(不自动收起)`,unlock:`解锁目录`,close:`关闭目录`}}),n(`en`,{messageToc:{toggleTitle:`Show table of contents (H{count} headings)`,title:`Contents`,headingCount:`{count}`,lock:`Pin table of contents`,unlock:`Unpin table of contents`,close:`Close table of contents`}});var vn=`messageTocLocked`,yn=!1,bn=`<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>`,xn=`<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`;function Sn(e){e&&(e.innerHTML=yn?xn:bn,e.title=r(yn?`messageToc.unlock`:`messageToc.lock`),e.classList.toggle(`locked`,yn))}function Cn(){try{let e=chrome.storage?.local?.set?.({[vn]:yn});e&&typeof e.catch==`function`&&e.catch(()=>{})}catch{}}function wn(){document.addEventListener(`mouseover`,Tn,!0),document.addEventListener(`mouseout`,En,!0);try{let e=chrome.storage?.local?.get?.(vn);e&&typeof e.then==`function`?e.then(e=>{yn=!!(e&&e[vn])}).catch(()=>{}):e&&typeof e==`object`&&(yn=!!e[vn])}catch{}i.debug(`[SidePanel] messagedirectory featureinitializing`)}function Tn(e){if(!(e.target instanceof Element))return;if(e.target.closest(`.message-toc-container`)){C.isMouseOverToc=!0;return}let t=e.target.closest(`.message.assistant`),n=e.target.closest(`.workspace-preview-markdown`);if(!t&&!n)return;let r=t||n,i=r.querySelectorAll(`.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6`);if(i.length===0){yn||Nn();return}Mn(r,i)}function En(e){if(!(e.target instanceof Element))return;if(e.target.closest(`.message-toc-container`)){C.isMouseOverToc=!1,C.tocHideTimer&&=(clearTimeout(C.tocHideTimer),null);return}let t=e.target.closest(`.message.assistant`),n=e.target.closest(`.workspace-preview-markdown`);if(!t&&!n||yn)return;let r=e.relatedTarget;r&&(r.closest(`.message-toc-container`)||r.closest(`.message.assistant`)||r.closest(`.workspace-preview-markdown`))||C.isMouseOverToc||(C.tocHideTimer&&clearTimeout(C.tocHideTimer),C.tocHideTimer=setTimeout(()=>{C.isMouseOverToc||Nn(),C.tocHideTimer=null},800))}var Dn=null,On=null;function kn(e){let t=e.parentElement;for(;t&&t!==document.body&&t!==document.documentElement;){let e=getComputedStyle(t).overflowY;if((e===`auto`||e===`scroll`||e===`overlay`)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null}function An(e,t,n,r){if(jn(),n.length===0)return;let i=kn(t),a=e.querySelector(`.message-toc-content`),o=Array.from(e.querySelectorAll(`.message-toc-item`)),s=new Map(o.map(e=>[e.dataset.target,e])),c=0,l=null,u=-1,d=e=>{if(!a)return;let t=e.getBoundingClientRect(),n=a.getBoundingClientRect();(t.top<n.top||t.bottom>n.bottom)&&(a.scrollTop+=t.top-n.top-(n.height-t.height)/2)},f=()=>{let e=window.innerHeight||document.documentElement.clientHeight||0;if(!i)return{top:0,bottom:e};let t=i.getBoundingClientRect();return{top:Math.max(t.top,0),bottom:Math.min(t.top+i.clientHeight,e)}},p=()=>{if(i)return i.scrollTop+i.clientHeight>=i.scrollHeight-2;let e=document.documentElement;return window.scrollY+window.innerHeight>=e.scrollHeight-2},m=()=>i?i.scrollTop<=2:window.scrollY<=2,h=()=>{if(c=0,!e.isConnected)return;let t=f(),i=t.top,a=t.bottom,h=Math.max(a-i,1),g=n.map(e=>e.getBoundingClientRect().top),_=0;for(let e=0;e<g.length&&g[e]<=i;e++)_=e;let v=i+h*.75,y=_,b=_+1;if(b<g.length){let e=g[b];u===b?e<=a&&(y=b):e<=v&&(y=b)}m()?y=0:p()&&(y=n.length-1);let x=n[y];if(!x||x.id===l)return;u=y,l=x.id,o.forEach(e=>e.classList.toggle(`active`,e.dataset.target===l));let S=s.get(l);S&&r.classList.contains(`expanded`)&&d(S)},g=()=>{c||=requestAnimationFrame(h)};document.addEventListener(`scroll`,g,{capture:!0,passive:!0}),window.addEventListener(`resize`,g,{passive:!0});let _=typeof IntersectionObserver==`function`?new IntersectionObserver(g,{threshold:[0,.25,.5,.75,1]}):null;_&&n.forEach(e=>_.observe(e)),h(),On=()=>{if(h(),!l)return;let e=s.get(l);e&&d(e)},Dn=()=>{c&&cancelAnimationFrame(c),c=0,document.removeEventListener(`scroll`,g,{capture:!0}),window.removeEventListener(`resize`,g),_&&_.disconnect()}}function jn(){Dn&&=(Dn(),null),On=null}function Mn(e,t){let n=Array.from(t);C.messageTocContainer&&Nn(),n.forEach((e,t)=>{e.id||=`toc-heading-${Date.now()}-${t}`});let i=document.createElement(`div`);i.className=`message-toc-container`,i.dataset.headingsCount=n.length;let a=0,o=n.map(e=>{let t=parseInt(e.tagName.charAt(1)),n=e.textContent.trim(),r=n.length>30?n.substring(0,30)+`...`:n,i=`H${t}`;return a++,`
|
|
4
4
|
<li class="message-toc-item level-${t}"
|
|
5
5
|
data-target="${e.id}"
|
|
6
6
|
data-anchor="${i}"
|
|
@@ -26,38 +26,38 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
26
26
|
</ul>
|
|
27
27
|
</div>
|
|
28
28
|
</div>
|
|
29
|
-
`;let s=e.closest(`.message-fullscreen-overlay`),c=e.closest(`.workspace-preview-overlay.fullscreen`);(s?s.querySelector(`.message-fullscreen-rail`)||hn(`toc`):c&&c.querySelector(`.workspace-preview-rail`)||hn(`toc`)).appendChild(i),C.messageTocContainer=i;let l=i.querySelector(`.message-toc-toggle`),u=i.querySelector(`.message-toc-panel`);yn&&(u.classList.add(`expanded`,`locked`),Be(u));let d=i.querySelector(`.message-toc-lock`);d.addEventListener(`click`,e=>{e.stopPropagation(),yn=!yn,Cn(),Sn(d),yn?(u.classList.add(`expanded`,`locked`),Be(u),requestAnimationFrame(()=>On&&On())):u.classList.remove(`locked`)}),i.querySelector(`.message-toc-close`).addEventListener(`click`,e=>{e.stopPropagation(),yn&&(yn=!1,Cn()),Nn()}),l.addEventListener(`mouseenter`,()=>{u.classList.add(`expanded`),Be(u),requestAnimationFrame(()=>On&&On())}),l.addEventListener(`click`,()=>{u.classList.toggle(`expanded`)?(Be(u),requestAnimationFrame(()=>On&&On())):Re(u)}),u.addEventListener(`mouseenter`,()=>{u.classList.add(`expanded`),requestAnimationFrame(()=>On&&On())}),i.querySelectorAll(`.message-toc-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.target,n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),n.classList.add(`toc-highlight`),setTimeout(()=>{n.classList.remove(`toc-highlight`)},1500))})}),An(i,e,n,u)}function Nn(){C.tocHideTimer&&=(clearTimeout(C.tocHideTimer),null),jn(),C.messageTocContainer&&=(C.messageTocContainer.remove(),null)}var Pn=`promptQueues`,Fn=1,In=30*1e3,Ln=15*1e3,Rn=20,L={QUEUED:`queued`,DISPATCHING:`dispatching`,INJECTING:`injecting`,INJECTED:`injected`,DONE:`done`,FAILED:`failed`};new Set([L.INJECTED,L.DONE,L.FAILED]);var zn={async get(e){let t=await chrome.storage.local.get(e);return t?t[e]:void 0},async set(e){await chrome.storage.local.set(e)}};function Bn(){return{version:Fn,sessions:{}}}var R=Bn(),Vn=!1,Hn=null,Un=!1,Wn=``,Gn=new Set,Kn=new Set;function qn(){return{items:[],recent:[],paused:!1,pausedReason:null}}function Jn(e){return e?(R.sessions[e]||(R.sessions[e]=qn()),R.sessions[e]):qn()}function Yn(){return JSON.stringify(R)}function Xn(e,t){for(let n of Kn)try{n(e,t)}catch(e){i.error(`[QueueStore] listener failed:`,e?.message)}}function Zn(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`q_`+crypto.randomUUID():`q_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8)}function Qn(e){return e.reduce((e,t)=>Math.max(e,Number(t.order)||0),0)+1}function $n(e,t){let n=e.indexOf(t);n<0||(e.splice(n,1),e.unshift(t),er(e))}function er(e){e.forEach((e,t)=>{e.order=t+1})}function tr(e){return e.slice().sort((e,t)=>(Number(e.order)||0)-(Number(t.order)||0))}async function nr(e){if(Un)return i.error(`[QueueStore] persist skipped in degraded mode:`,e),!1;let t=Yn();Wn=t,rr(t);try{await zn.set({[Pn]:R})}catch(e){i.error(`[QueueStore] persist failed:`,e?.message)}Xn(e)}function rr(e){if(Gn.add(e),Gn.size<=Rn)return;let t=Gn.values().next().value;Gn.delete(t)}function ir(e,{recoverInterrupted:t=!0}={}){let n=Bn();if(!e||typeof e!=`object`)return n;let r=e.sessions&&typeof e.sessions==`object`?e.sessions:{};for(let[e,i]of Object.entries(r)){let r=Array.isArray(i?.items)?i.items:[],a=Array.isArray(i?.recent)?i.recent.slice(0,30):[],o=!1;for(let e of r)!e||typeof e!=`object`||t&&(e.status===L.DISPATCHING||e.status===L.INJECTING)&&(e.status=L.QUEUED,e.interrupted=!0,e.previousStatus=e.previousStatus||L.DISPATCHING,e.leaseOwner=null,e.leaseUntil=0,o=!0);let s=tr(r);if(o){let e=s.filter(e=>e.interrupted),t=s.filter(e=>!e.interrupted);s.splice(0,s.length,...e,...t)}er(s);let c=s.slice(0,20),l=s.slice(20);for(let e of l.reverse())a.unshift(Dr({...e,status:L.FAILED,lastError:`over_limit`}));n.sessions[e]={items:c,recent:a.slice(0,30),paused:i?.paused===!0,pausedReason:i?.pausedReason||null}}return n}function ar(){return Un}async function or(){return Vn?R:Hn||(Hn=(async()=>{let e;try{e=await zn.get(Pn)}catch(e){return Un=!0,Hn=null,i.error(`[QueueStore] load failed, enter degraded mode:`,e?.message),R}return R=ir(e),Vn=!0,Un=!1,Wn=Yn(),R})(),Hn)}function sr(){typeof chrome>`u`||!chrome.storage?.onChanged?.addListener||chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`||!e?.[Pn])return;let n=e[Pn].newValue;if(!n)return;let r=JSON.stringify(n);Gn.has(r)||r===Wn||(R=ir(n,{recoverInterrupted:!1}),Vn=!0,Wn=r,Xn(`external`,null))})}function cr(e){return typeof e==`function`?(Kn.add(e),()=>Kn.delete(e)):()=>{}}function lr(e){let t=R.sessions[e];return t?tr(t.items):[]}function ur(e,t=30){let n=R.sessions[e];return n?n.recent.slice(0,t):[]}function dr(e){let t=R.sessions[e];return t?{items:tr(t.items),recent:t.recent.slice(),paused:t.paused===!0,pausedReason:t.pausedReason||null}:qn()}function fr(e){return lr(e).filter(e=>e.status===L.QUEUED).length}function pr(e){return lr(e).find(e=>e.status===L.QUEUED)||null}function mr(e){let t=R.sessions[e];if(!t)return null;for(let e=t.items.length-1;e>=0;--e)if(t.items[e].status===L.QUEUED)return t.items[e];return null}function hr(e,t){let n=R.sessions[e];return n&&n.items.find(e=>e.id===t)||null}function gr(){return Object.keys(R.sessions).filter(e=>(R.sessions[e]?.items?.length||0)>0)}function _r(e){return R.sessions[e]?.paused===!0}async function vr({sessionId:e,text:t,contextSnapshot:n=null,hasContext:r=!1,attachmentSummary:i=null,source:a=`manual`}){if(!e)return{ok:!1,error:`missing_session`};let o=String(t||``).trim();if(!o)return{ok:!1,error:`empty`};if(await or(),Un)return{ok:!1,error:`storage_unavailable`};let s=Jn(e);if(s.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let c={id:Zn(),sessionId:e,text:o,contextSnapshot:n||null,attachmentSummary:i||null,hasContext:r===!0,status:L.QUEUED,order:Qn(s.items),createdAt:Date.now(),updatedAt:Date.now(),attempts:0,lastError:null,source:a,interrupted:!1,leaseOwner:null,leaseUntil:0,injectRequestedAt:0,injectDeadlineAt:0,injectedIntoCallId:null,absorbedIteration:null};return s.items.push(c),await nr(`enqueue`),{ok:!0,item:c,position:s.items.length}}async function yr(e,t){let n=R.sessions[e];if(!n)return!1;let r=n.items.findIndex(e=>e.id===t);return r<0?!1:(n.items.splice(r,1),er(n.items),await nr(`remove`),!0)}async function br(e,t){let n=R.sessions[e];if(!n||!Array.isArray(t))return!1;let r=new Map(n.items.map(e=>[e.id,e])),i=[];for(let e of t){let t=r.get(e);t&&!i.includes(t)&&i.push(t)}for(let e of tr(n.items))i.includes(e)||i.push(e);return n.items=i,er(n.items),await nr(`reorder`),!0}async function xr(e,t,n,r={}){let i=hr(e,t);return i?(i.status=n,Object.assign(i,r,{updatedAt:Date.now()}),await nr(`status`),!0):!1}async function Sr(e,t,n=Ln){let r=hr(e,t);return r?(r.previousStatus=r.status,r.status=L.INJECTING,r.injectRequestedAt=Date.now(),r.injectDeadlineAt=Date.now()+n,r.updatedAt=Date.now(),await nr(`inject:request`),!0):!1}async function Cr(e,t,n=`error`,r=null){let i=R.sessions[e];if(!i)return!1;let a=i.items.find(e=>e.id===t);return a?(a.status=L.QUEUED,a.injectDeadlineAt=0,a.updatedAt=Date.now(),a.lastError=r||n,a.rollbackReason=n,$n(i.items,a),await nr(`inject:rollback`),!0):!1}async function wr(e,t,{status:n,note:r=null,callId:i=null,iteration:a=null}={}){let o=R.sessions[e];if(!o)return!1;let s=o.items.findIndex(e=>e.id===t);if(s<0)return!1;let[c]=o.items.splice(s,1);return er(o.items),c.status=n||L.DONE,c.settledAt=Date.now(),c.settleNote=r,i&&(c.injectedIntoCallId=i),a!=null&&(c.absorbedIteration=a),o.recent.unshift(Dr(c)),o.recent=o.recent.slice(0,30),await nr(`settle`),!0}async function Tr(e,t){let n=R.sessions[e];if(!n)return{ok:!1,error:`missing_session`};let r=n.recent.findIndex(e=>e.id===t);if(r<0)return{ok:!1,error:`not_found`};if(n.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let[i]=n.recent.splice(r,1),a={...i,status:L.QUEUED,order:Qn(n.items),attempts:0,lastError:null,interrupted:!1,rollbackReason:null,settledAt:null,leaseOwner:null,leaseUntil:0,injectDeadlineAt:0,updatedAt:Date.now()};return n.items.push(a),await nr(`requeue`),{ok:!0,item:a}}async function Er(e,t){let n=R.sessions[e];if(!n)return!1;let r=n.recent.findIndex(e=>e.id===t);return r<0?!1:(n.recent.splice(r,1),await nr(`recent-remove`),!0)}function Dr(e){let{leaseOwner:t,leaseUntil:n,injectDeadlineAt:r,contextSnapshot:i,...a}=e;return{...a,hasContext:e.hasContext===!0,contextDropped:!!i}}async function Or(e,t=`user_stopped`){let n=Jn(e);return n.paused?!1:(n.paused=!0,n.pausedReason=t,await nr(`pause`),!0)}async function kr(e){let t=R.sessions[e];return!t||!t.paused?!1:(t.paused=!1,t.pausedReason=null,await nr(`resume`),!0)}async function Ar(e,t,n){let r=hr(e,t);if(!r)return!1;let i=Date.now();return r.leaseOwner&&r.leaseOwner!==n&&Number(r.leaseUntil)>i?!1:(r.leaseOwner=n,r.leaseUntil=i+In,await nr(`lease`),!0)}async function jr(e){let t=R.sessions[e];if(!t)return 0;let n=t.items.length+t.recent.length;return delete R.sessions[e],n>0&&await nr(`drop-session`),n}var Mr=`ai-helper-queue-attachments`,Nr=1,Pr=`attachments`,Fr=null,Ir=null;function Lr(){return new Promise((e,t)=>{let n=indexedDB.open(Mr,Nr);n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(Pr)||t.createObjectStore(Pr,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})},n.onsuccess=t=>{let n=t.target.result;n.onversionchange=()=>{try{n.close()}catch{}Fr=null},e(n)},n.onerror=()=>t(n.error||Error(`idb_open_failed`)),n.onblocked=()=>{}})}function Rr(){return Fr||=Lr(),Fr}function zr(e,t){return Rr().then(n=>new Promise((r,i)=>{let a;try{a=n.transaction(Pr,e)}catch(e){Fr=null,i(e);return}let o=a.objectStore(Pr),s=null,c=e=>{s=e};try{t(o,c)}catch(e){i(e);return}a.oncomplete=()=>r(s),a.onerror=()=>i(a.error||Error(`idb_tx_failed`)),a.onabort=()=>i(a.error||Error(`idb_tx_aborted`))}))}function Br(){return{async put(e){await zr(`readwrite`,t=>{t.put(e)})},async get(e){return zr(`readonly`,(t,n)=>{let r=t.get(e);r.onsuccess=()=>n(r.result||null)})},async remove(e){await zr(`readwrite`,t=>{t.delete(e)})},async removeBySession(e){await zr(`readwrite`,t=>{let n=t.index(`sessionId`).getAllKeys(e);n.onsuccess=()=>{for(let e of n.result||[])t.delete(e)}})},async allKeys(){return zr(`readonly`,(e,t)=>{let n=e.getAllKeys();n.onsuccess=()=>t(n.result||[])})}}}function Vr(){return Ir||Br()}function Hr(e){return e==null?0:typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?8:Array.isArray(e)?e.reduce((e,t)=>e+Hr(t),0):typeof e==`object`?Object.values(e).reduce((e,t)=>e+Hr(t),0):0}function Ur(e){let t=e&&e.attachedImages||[],n=e&&e.attachedFiles||[];return!t.length&&!n.length?null:{imageCount:t.length,fileCount:n.length,fileNames:n.map(e=>e.name).filter(Boolean).slice(0,5)}}async function Wr(e,t,{images:n=[],files:r=[]}={}){if(!e)return{ok:!1,reason:`missing_id`};if(!n.length&&!r.length)return{ok:!0,skipped:!0};let i=Hr(n)+Hr(r);if(i>26214400)return{ok:!1,reason:`too_large`,size:i};try{return await Vr().put({id:e,sessionId:t||null,size:i,images:n,files:r,updatedAt:Date.now()}),{ok:!0,size:i}}catch(e){return{ok:!1,reason:`idb_error`,message:e?.message||String(e)}}}async function Gr(e){if(!e)return null;try{let t=await Vr().get(e);return t?{images:t.images||[],files:t.files||[]}:null}catch{return null}}async function Kr(e){if(!e)return!1;try{return await Vr().remove(e),!0}catch{return!1}}async function qr(e){if(!e)return!1;try{return await Vr().removeBySession(e),!0}catch{return!1}}async function Jr(e){let t=e instanceof Set?e:new Set(e||[]);try{let e=await Vr().allKeys(),n=0;for(let r of e||[])t.has(r)||(await Vr().remove(r),n+=1);return n}catch{return 0}}var Yr=t({appendMessageToSession:()=>_i,archiveCurrentSession:()=>ui,archiveSession:()=>pi,clearSessionCompleted:()=>ei,createSession:()=>ai,deleteArchivedSession:()=>hi,deleteSession:()=>si,duplicateSession:()=>vi,hydrateSessionWorkdir:()=>ri,importSessions:()=>gi,isSessionArchivable:()=>fi,loadArchivedSessions:()=>di,loadSessions:()=>ti,markSessionCompleted:()=>$r,persistSessionState:()=>ii,renameSession:()=>ci,reorderSessions:()=>li,restoreCompletedSessions:()=>Zr,restoreSession:()=>mi,saveCurrentSession:()=>ni,switchToSession:()=>oi}),Xr=`completedSessionIds`;async function Zr(){try{let e=(await chrome.storage.local.get([Xr]))[Xr]||[];C.completedSessionIds=new Set(e)}catch(e){i.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function Qr(){try{await chrome.storage.local.set({[Xr]:Array.from(C.completedSessionIds)})}catch(e){i.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function $r(e){e&&e!==C.activeSessionId&&(C.completedSessionIds.has(e)||(C.completedSessionIds.add(e),await Qr(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function ei(e){e&&C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await Qr(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function ti(){return le()}async function ni(){return de()}function ri(e){return ce(e)}async function ii(e,t){return ue(e,t)}async function ai(){return oe()}async function oi(e){return Ce(e)}async function si(e){await jr(e)>0&&qr(e);let t=await _e(e);try{chrome.runtime.sendMessage({type:`DROP_GOAL`,sessionId:e},()=>{chrome.runtime.lastError&&i.debug(`[SessionManager] DROP_GOAL skipped:`,chrome.runtime.lastError.message)})}catch(e){i.debug(`[SessionManager] DROP_GOAL send failed:`,e?.message)}return C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await Qr()),t}async function ci(e,t){return ve(e,t)}async function li(e){return he(e)}async function ui(){return ge()}async function di(){return Se()}function fi(e){return e?C.generatingSessionIds.has(e)||C.pendingCallApiSessionIds.has(e)?{ok:!1,reason:`running`}:fr(e)>0?{ok:!1,reason:`queued`}:{ok:!0}:{ok:!1,reason:`missing`}}async function pi(e){let t=fi(e);return t.ok?await ye(e)?(C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await Qr(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))),{ok:!0}):{ok:!1,reason:`missing`}:t}async function mi(e){return Ee(e)}async function hi(e){return si(e)}async function gi(e){return me(e)}async function _i(e,t){return xe(e,t)}async function vi(e,t=null){return be(e,t)}n(`zh`,{toolPanel:{agentRestrictedBanner:`当前 Agent 限制了可用工具,部分工具已禁用`,noMatch:`没有匹配的工具`,enabledCount:`已启用 {enabled}/{total} 个工具`,toolsEnabled:`工具已启用`,allToolsDisabled:`所有工具已禁用`,toggleBtnEnabled:`禁用所有工具`,toggleBtnDisabled:`启用所有工具`,mcpServiceToolCount:`{count} 个工具`,mcpServiceExpand:`展开/收起工具列表`,mcpExcludedByAgent:`已被当前助手排除,可在助手编辑中调整`,categorySelectAllHint:`对该分类下可见项全选/取消全选`,stateOn:`已开启`,stateOff:`已关闭`,stateLine:`{name}:{state}`}}),n(`en`,{toolPanel:{agentRestrictedBanner:`Current agent has restricted available tools, some tools are disabled`,noMatch:`No matching tools`,enabledCount:`{enabled}/{total} tools enabled`,toolsEnabled:`Tools enabled`,allToolsDisabled:`All tools disabled`,toggleBtnEnabled:`Disable all tools`,toggleBtnDisabled:`Enable all tools`,mcpServiceToolCount:`{count} tools`,mcpServiceExpand:`Show/hide tool list`,mcpExcludedByAgent:`Excluded by current assistant; adjust in assistant editor`,categorySelectAllHint:`Select/deselect all visible items in this category`,stateOn:`On`,stateOff:`Off`,stateLine:`{name}: {state}`}});var yi=[],bi=[];function xi(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function Si(e){if(!e)return``;let t=e.description||``;if(t.startsWith(`[MCP:`)){let e=t.indexOf(`]`);e!==-1&&(t=t.slice(e+1).trim())}return t===(e.name||``)?``:t}async function Ci(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return yi=e.tools,yi}catch{}try{return yi=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],yi}catch{return yi=[],[]}}async function wi(){try{bi=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{bi=[]}return bi}async function Ti(){let e=`agentMcpClosedServers_${C.activeAgentId||`default`}`;try{C.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}catch{C.mcpClosedServers=[]}try{let{getAgent:e}=await A(async()=>{let{getAgent:e}=await import(`./agent-store-CE4-QMOA.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3])),t=C.activeAgentId?await e(C.activeAgentId):null;C.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null}catch{}}var Ei=!1,Di=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{Ei=e.enableToolPreselect===!0,Di=e.toolConfirmationEnabled!==!1,$i()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&(yi=e.mcpTools.newValue||[],i.debug(`[SidePanel] MCP toolcache updated:`,yi.length,``),n=!0),e.ragTools&&(bi=e.ragTools.newValue||[],i.debug(`[SidePanel] RAG toolcache updated:`,bi.length),n=!0),e.mcpEnabled&&(Oi=e.mcpEnabled.newValue===!0,i.debug(`[SidePanel] MCP globaltoggle changed:`,Oi),n=!0),e.skillsEnabled&&(ki=e.skillsEnabled.newValue!==!1,i.debug(`[SidePanel] Skill global toggle changed:`,ki),n=!0),e.enableImageInput&&(Ai=e.enableImageInput.newValue===!0,i.debug(`[SidePanel] 图片识别全局开关变更:`,Ai),n=!0);let r=!1;e.enableToolPreselect&&(Ei=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(Di=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&$i(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Ji(),Yi(),Bi()),Qi())}),Ci().then(()=>Qi()),wi().then(()=>Qi());var Oi=!1,ki=!0,Ai=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{Oi=e.mcpEnabled===!0,ki=e.skillsEnabled!==!1,Ai=e.enableImageInput===!0,Qi()});function ji(){let e=[...f,...bi],t=C.activeAgentToolIds,n=e;if(t!=null){let r=new Set(t);n=e.filter(e=>r.has(e.id))}return ki||(n=n.filter(e=>e.id!==`agent_skill`)),C.agentPlatform?.connected!==!0&&(n=n.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),Ai||(n=n.filter(e=>e.id!==`read_image`)),n}function Mi(){if(!Oi||C.agentPlatform?.connected!==!0)return[];let e=new Map;return yi.forEach(t=>{let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[],toolCount:0});let r=e.get(n);r.tools.push(t),r.toolCount++}),Array.from(e.values())}function Ni(e){return Array.isArray(C.mcpClosedServers)&&C.mcpClosedServers.includes(e)}function Pi(e){return Array.isArray(C.activeAgentMcpExcludedServerIds)&&C.activeAgentMcpExcludedServerIds.includes(e)}function Fi(e){return!Ni(e)&&!Pi(e)}function Ii(){if(C.currentCategory!==`all`&&C.currentCategory!==`mcp`)return[];let e=Mi();if(C.currentSearch){let t=C.currentSearch;e=e.filter(e=>(e.serverName||``).toLowerCase().includes(t)||(e.serverId||``).toLowerCase().includes(t)||e.tools.some(e=>(e.name||``).toLowerCase().includes(t)||xi(e).toLowerCase().includes(t)))}return e}function Li(e,t){Array.isArray(C.mcpClosedServers)||(C.mcpClosedServers=[]);let n=C.mcpClosedServers.indexOf(e);t?n>-1&&C.mcpClosedServers.splice(n,1):n===-1&&C.mcpClosedServers.push(e)}async function Ri(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;C.currentCategory=`all`,C.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await Ci(),await wi(),await Ti(),Ji(),Yi(),chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{let t=document.getElementById(`toolsPreselectToggle`);t&&(t.checked=e.enableToolPreselect===void 0?!1:e.enableToolPreselect);let n=document.getElementById(`toolConfirmToggle`);n&&(n.checked=e.toolConfirmationEnabled===void 0?!0:e.toolConfirmationEnabled)}),document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),Bi(),e.classList.add(`show`),i.debug(`[SidePanel] opentool popup`)}function zi(){let e=document.getElementById(`toolsPopupOverlay`);e&&(document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.style.background=``,e.style.color=``,e.style.borderColor=``}),e.classList.remove(`show`),i.debug(`[SidePanel] closetool popup`))}function Bi(){let e=document.getElementById(`toolsPopupList`);if(!e)return;e.innerHTML=``;let t=ji();if(C.activeAgentToolIds!==null&&C.activeAgentToolIds!==void 0){let t=document.createElement(`div`);t.className=`popup-tool-agent-banner`,t.innerHTML=`<span>${r(`toolPanel.agentRestrictedBanner`)}</span>`,e.appendChild(t)}let n={};t.forEach(e=>{if(C.currentCategory!==`all`&&e.category!==C.currentCategory)return;if(C.currentSearch){let t=e.name.toLowerCase().includes(C.currentSearch),n=xi(e).toLowerCase().includes(C.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=Ii();if(Zt.forEach(a=>{let o=a===`mcp`,s=n[a]||[],c=o?i:[];if(o?c.length===0:s.length===0)return;let l;if(o)l=`${c.filter(e=>Fi(e.serverId)).length}/${c.length}`;else{let e=t.filter(e=>e.category===a);l=`${e.filter(e=>C.enabledTools.includes(e.id)).length}/${e.length}`}let u=document.createElement(`div`);u.className=`popup-tool-category-group`,u.dataset.category=a;let d=document.createElement(`div`);d.className=`popup-tool-category`,d.dataset.category=a;let f=C.collapsedCategories[a]||!1;d.innerHTML=`
|
|
29
|
+
`;let s=e.closest(`.message-fullscreen-overlay`),c=e.closest(`.workspace-preview-overlay.fullscreen`);(s?s.querySelector(`.message-fullscreen-rail`)||hn(`toc`):c&&c.querySelector(`.workspace-preview-rail`)||hn(`toc`)).appendChild(i),C.messageTocContainer=i;let l=i.querySelector(`.message-toc-toggle`),u=i.querySelector(`.message-toc-panel`);yn&&(u.classList.add(`expanded`,`locked`),Fe(u));let d=i.querySelector(`.message-toc-lock`);d.addEventListener(`click`,e=>{e.stopPropagation(),yn=!yn,Cn(),Sn(d),yn?(u.classList.add(`expanded`,`locked`),Fe(u),requestAnimationFrame(()=>On&&On())):u.classList.remove(`locked`)}),i.querySelector(`.message-toc-close`).addEventListener(`click`,e=>{e.stopPropagation(),yn&&(yn=!1,Cn()),Nn()}),l.addEventListener(`mouseenter`,()=>{u.classList.add(`expanded`),Fe(u),requestAnimationFrame(()=>On&&On())}),l.addEventListener(`click`,()=>{u.classList.toggle(`expanded`)?(Fe(u),requestAnimationFrame(()=>On&&On())):Le(u)}),u.addEventListener(`mouseenter`,()=>{u.classList.add(`expanded`),requestAnimationFrame(()=>On&&On())}),i.querySelectorAll(`.message-toc-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.target,n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),n.classList.add(`toc-highlight`),setTimeout(()=>{n.classList.remove(`toc-highlight`)},1500))})}),An(i,e,n,u)}function Nn(){C.tocHideTimer&&=(clearTimeout(C.tocHideTimer),null),jn(),C.messageTocContainer&&=(C.messageTocContainer.remove(),null)}var Pn=`promptQueues`,Fn=1,In=30*1e3,Ln=15*1e3,Rn=20,L={QUEUED:`queued`,DISPATCHING:`dispatching`,INJECTING:`injecting`,INJECTED:`injected`,DONE:`done`,FAILED:`failed`};new Set([L.INJECTED,L.DONE,L.FAILED]);var zn={async get(e){let t=await chrome.storage.local.get(e);return t?t[e]:void 0},async set(e){await chrome.storage.local.set(e)}};function Bn(){return{version:Fn,sessions:{}}}var R=Bn(),Vn=!1,Hn=null,Un=!1,Wn=``,Gn=new Set,Kn=new Set;function qn(){return{items:[],recent:[],paused:!1,pausedReason:null}}function Jn(e){return e?(R.sessions[e]||(R.sessions[e]=qn()),R.sessions[e]):qn()}function Yn(){return JSON.stringify(R)}function Xn(e,t){for(let n of Kn)try{n(e,t)}catch(e){i.error(`[QueueStore] listener failed:`,e?.message)}}function Zn(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`q_`+crypto.randomUUID():`q_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8)}function Qn(e){return e.reduce((e,t)=>Math.max(e,Number(t.order)||0),0)+1}function $n(e,t){let n=e.indexOf(t);n<0||(e.splice(n,1),e.unshift(t),er(e))}function er(e){e.forEach((e,t)=>{e.order=t+1})}function tr(e){return e.slice().sort((e,t)=>(Number(e.order)||0)-(Number(t.order)||0))}async function nr(e){if(Un)return i.error(`[QueueStore] persist skipped in degraded mode:`,e),!1;let t=Yn();Wn=t,rr(t);try{await zn.set({[Pn]:R})}catch(e){i.error(`[QueueStore] persist failed:`,e?.message)}Xn(e)}function rr(e){if(Gn.add(e),Gn.size<=Rn)return;let t=Gn.values().next().value;Gn.delete(t)}function ir(e,{recoverInterrupted:t=!0}={}){let n=Bn();if(!e||typeof e!=`object`)return n;let r=e.sessions&&typeof e.sessions==`object`?e.sessions:{};for(let[e,i]of Object.entries(r)){let r=Array.isArray(i?.items)?i.items:[],a=Array.isArray(i?.recent)?i.recent.slice(0,30):[],o=!1;for(let e of r)!e||typeof e!=`object`||t&&(e.status===L.DISPATCHING||e.status===L.INJECTING)&&(e.status=L.QUEUED,e.interrupted=!0,e.previousStatus=e.previousStatus||L.DISPATCHING,e.leaseOwner=null,e.leaseUntil=0,o=!0);let s=tr(r);if(o){let e=s.filter(e=>e.interrupted),t=s.filter(e=>!e.interrupted);s.splice(0,s.length,...e,...t)}er(s);let c=s.slice(0,20),l=s.slice(20);for(let e of l.reverse())a.unshift(Dr({...e,status:L.FAILED,lastError:`over_limit`}));n.sessions[e]={items:c,recent:a.slice(0,30),paused:i?.paused===!0,pausedReason:i?.pausedReason||null}}return n}function ar(){return Un}async function or(){return Vn?R:Hn||(Hn=(async()=>{let e;try{e=await zn.get(Pn)}catch(e){return Un=!0,Hn=null,i.error(`[QueueStore] load failed, enter degraded mode:`,e?.message),R}return R=ir(e),Vn=!0,Un=!1,Wn=Yn(),R})(),Hn)}function sr(){typeof chrome>`u`||!chrome.storage?.onChanged?.addListener||chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`||!e?.[Pn])return;let n=e[Pn].newValue;if(!n)return;let r=JSON.stringify(n);Gn.has(r)||r===Wn||(R=ir(n,{recoverInterrupted:!1}),Vn=!0,Wn=r,Xn(`external`,null))})}function cr(e){return typeof e==`function`?(Kn.add(e),()=>Kn.delete(e)):()=>{}}function lr(e){let t=R.sessions[e];return t?tr(t.items):[]}function ur(e,t=30){let n=R.sessions[e];return n?n.recent.slice(0,t):[]}function dr(e){let t=R.sessions[e];return t?{items:tr(t.items),recent:t.recent.slice(),paused:t.paused===!0,pausedReason:t.pausedReason||null}:qn()}function fr(e){return lr(e).filter(e=>e.status===L.QUEUED).length}function pr(e){return lr(e).find(e=>e.status===L.QUEUED)||null}function mr(e){let t=R.sessions[e];if(!t)return null;for(let e=t.items.length-1;e>=0;--e)if(t.items[e].status===L.QUEUED)return t.items[e];return null}function hr(e,t){let n=R.sessions[e];return n&&n.items.find(e=>e.id===t)||null}function gr(){return Object.keys(R.sessions).filter(e=>(R.sessions[e]?.items?.length||0)>0)}function _r(e){return R.sessions[e]?.paused===!0}async function vr({sessionId:e,text:t,contextSnapshot:n=null,hasContext:r=!1,attachmentSummary:i=null,source:a=`manual`}){if(!e)return{ok:!1,error:`missing_session`};let o=String(t||``).trim();if(!o)return{ok:!1,error:`empty`};if(await or(),Un)return{ok:!1,error:`storage_unavailable`};let s=Jn(e);if(s.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let c={id:Zn(),sessionId:e,text:o,contextSnapshot:n||null,attachmentSummary:i||null,hasContext:r===!0,status:L.QUEUED,order:Qn(s.items),createdAt:Date.now(),updatedAt:Date.now(),attempts:0,lastError:null,source:a,interrupted:!1,leaseOwner:null,leaseUntil:0,injectRequestedAt:0,injectDeadlineAt:0,injectedIntoCallId:null,absorbedIteration:null};return s.items.push(c),await nr(`enqueue`),{ok:!0,item:c,position:s.items.length}}async function yr(e,t){let n=R.sessions[e];if(!n)return!1;let r=n.items.findIndex(e=>e.id===t);return r<0?!1:(n.items.splice(r,1),er(n.items),await nr(`remove`),!0)}async function br(e,t){let n=R.sessions[e];if(!n||!Array.isArray(t))return!1;let r=new Map(n.items.map(e=>[e.id,e])),i=[];for(let e of t){let t=r.get(e);t&&!i.includes(t)&&i.push(t)}for(let e of tr(n.items))i.includes(e)||i.push(e);return n.items=i,er(n.items),await nr(`reorder`),!0}async function xr(e,t,n,r={}){let i=hr(e,t);return i?(i.status=n,Object.assign(i,r,{updatedAt:Date.now()}),await nr(`status`),!0):!1}async function Sr(e,t,n=Ln){let r=hr(e,t);return r?(r.previousStatus=r.status,r.status=L.INJECTING,r.injectRequestedAt=Date.now(),r.injectDeadlineAt=Date.now()+n,r.updatedAt=Date.now(),await nr(`inject:request`),!0):!1}async function Cr(e,t,n=`error`,r=null){let i=R.sessions[e];if(!i)return!1;let a=i.items.find(e=>e.id===t);return a?(a.status=L.QUEUED,a.injectDeadlineAt=0,a.updatedAt=Date.now(),a.lastError=r||n,a.rollbackReason=n,$n(i.items,a),await nr(`inject:rollback`),!0):!1}async function wr(e,t,{status:n,note:r=null,callId:i=null,iteration:a=null}={}){let o=R.sessions[e];if(!o)return!1;let s=o.items.findIndex(e=>e.id===t);if(s<0)return!1;let[c]=o.items.splice(s,1);return er(o.items),c.status=n||L.DONE,c.settledAt=Date.now(),c.settleNote=r,i&&(c.injectedIntoCallId=i),a!=null&&(c.absorbedIteration=a),o.recent.unshift(Dr(c)),o.recent=o.recent.slice(0,30),await nr(`settle`),!0}async function Tr(e,t){let n=R.sessions[e];if(!n)return{ok:!1,error:`missing_session`};let r=n.recent.findIndex(e=>e.id===t);if(r<0)return{ok:!1,error:`not_found`};if(n.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let[i]=n.recent.splice(r,1),a={...i,status:L.QUEUED,order:Qn(n.items),attempts:0,lastError:null,interrupted:!1,rollbackReason:null,settledAt:null,leaseOwner:null,leaseUntil:0,injectDeadlineAt:0,updatedAt:Date.now()};return n.items.push(a),await nr(`requeue`),{ok:!0,item:a}}async function Er(e,t){let n=R.sessions[e];if(!n)return!1;let r=n.recent.findIndex(e=>e.id===t);return r<0?!1:(n.recent.splice(r,1),await nr(`recent-remove`),!0)}function Dr(e){let{leaseOwner:t,leaseUntil:n,injectDeadlineAt:r,contextSnapshot:i,...a}=e;return{...a,hasContext:e.hasContext===!0,contextDropped:!!i}}async function Or(e,t=`user_stopped`){let n=Jn(e);return n.paused?!1:(n.paused=!0,n.pausedReason=t,await nr(`pause`),!0)}async function kr(e){let t=R.sessions[e];return!t||!t.paused?!1:(t.paused=!1,t.pausedReason=null,await nr(`resume`),!0)}async function Ar(e,t,n){let r=hr(e,t);if(!r)return!1;let i=Date.now();return r.leaseOwner&&r.leaseOwner!==n&&Number(r.leaseUntil)>i?!1:(r.leaseOwner=n,r.leaseUntil=i+In,await nr(`lease`),!0)}async function jr(e){let t=R.sessions[e];if(!t)return 0;let n=t.items.length+t.recent.length;return delete R.sessions[e],n>0&&await nr(`drop-session`),n}var Mr=`ai-helper-queue-attachments`,Nr=1,Pr=`attachments`,Fr=null,Ir=null;function Lr(){return new Promise((e,t)=>{let n=indexedDB.open(Mr,Nr);n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(Pr)||t.createObjectStore(Pr,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})},n.onsuccess=t=>{let n=t.target.result;n.onversionchange=()=>{try{n.close()}catch{}Fr=null},e(n)},n.onerror=()=>t(n.error||Error(`idb_open_failed`)),n.onblocked=()=>{}})}function Rr(){return Fr||=Lr(),Fr}function zr(e,t){return Rr().then(n=>new Promise((r,i)=>{let a;try{a=n.transaction(Pr,e)}catch(e){Fr=null,i(e);return}let o=a.objectStore(Pr),s=null,c=e=>{s=e};try{t(o,c)}catch(e){i(e);return}a.oncomplete=()=>r(s),a.onerror=()=>i(a.error||Error(`idb_tx_failed`)),a.onabort=()=>i(a.error||Error(`idb_tx_aborted`))}))}function Br(){return{async put(e){await zr(`readwrite`,t=>{t.put(e)})},async get(e){return zr(`readonly`,(t,n)=>{let r=t.get(e);r.onsuccess=()=>n(r.result||null)})},async remove(e){await zr(`readwrite`,t=>{t.delete(e)})},async removeBySession(e){await zr(`readwrite`,t=>{let n=t.index(`sessionId`).getAllKeys(e);n.onsuccess=()=>{for(let e of n.result||[])t.delete(e)}})},async allKeys(){return zr(`readonly`,(e,t)=>{let n=e.getAllKeys();n.onsuccess=()=>t(n.result||[])})}}}function Vr(){return Ir||Br()}function Hr(e){return e==null?0:typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?8:Array.isArray(e)?e.reduce((e,t)=>e+Hr(t),0):typeof e==`object`?Object.values(e).reduce((e,t)=>e+Hr(t),0):0}function Ur(e){let t=e&&e.attachedImages||[],n=e&&e.attachedFiles||[];return!t.length&&!n.length?null:{imageCount:t.length,fileCount:n.length,fileNames:n.map(e=>e.name).filter(Boolean).slice(0,5)}}async function Wr(e,t,{images:n=[],files:r=[]}={}){if(!e)return{ok:!1,reason:`missing_id`};if(!n.length&&!r.length)return{ok:!0,skipped:!0};let i=Hr(n)+Hr(r);if(i>26214400)return{ok:!1,reason:`too_large`,size:i};try{return await Vr().put({id:e,sessionId:t||null,size:i,images:n,files:r,updatedAt:Date.now()}),{ok:!0,size:i}}catch(e){return{ok:!1,reason:`idb_error`,message:e?.message||String(e)}}}async function Gr(e){if(!e)return null;try{let t=await Vr().get(e);return t?{images:t.images||[],files:t.files||[]}:null}catch{return null}}async function Kr(e){if(!e)return!1;try{return await Vr().remove(e),!0}catch{return!1}}async function qr(e){if(!e)return!1;try{return await Vr().removeBySession(e),!0}catch{return!1}}async function Jr(e){let t=e instanceof Set?e:new Set(e||[]);try{let e=await Vr().allKeys(),n=0;for(let r of e||[])t.has(r)||(await Vr().remove(r),n+=1);return n}catch{return 0}}var Yr=t({appendMessageToSession:()=>_i,archiveCurrentSession:()=>ui,archiveSession:()=>pi,clearSessionCompleted:()=>ei,createSession:()=>ai,deleteArchivedSession:()=>hi,deleteSession:()=>si,duplicateSession:()=>vi,hydrateSessionWorkdir:()=>ri,importSessions:()=>gi,isSessionArchivable:()=>fi,loadArchivedSessions:()=>di,loadSessions:()=>ti,markSessionCompleted:()=>$r,persistSessionState:()=>ii,renameSession:()=>ci,reorderSessions:()=>li,restoreCompletedSessions:()=>Zr,restoreSession:()=>mi,saveCurrentSession:()=>ni,switchToSession:()=>oi}),Xr=`completedSessionIds`;async function Zr(){try{let e=(await chrome.storage.local.get([Xr]))[Xr]||[];C.completedSessionIds=new Set(e)}catch(e){i.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function Qr(){try{await chrome.storage.local.set({[Xr]:Array.from(C.completedSessionIds)})}catch(e){i.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function $r(e){e&&e!==C.activeSessionId&&(C.completedSessionIds.has(e)||(C.completedSessionIds.add(e),await Qr(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function ei(e){e&&C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await Qr(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function ti(){return le()}async function ni(){return de()}function ri(e){return ce(e)}async function ii(e,t){return ue(e,t)}async function ai(){return oe()}async function oi(e){return Ce(e)}async function si(e){await jr(e)>0&&qr(e);let t=await _e(e);try{chrome.runtime.sendMessage({type:`DROP_GOAL`,sessionId:e},()=>{chrome.runtime.lastError&&i.debug(`[SessionManager] DROP_GOAL skipped:`,chrome.runtime.lastError.message)})}catch(e){i.debug(`[SessionManager] DROP_GOAL send failed:`,e?.message)}return C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await Qr()),t}async function ci(e,t){return ve(e,t)}async function li(e){return he(e)}async function ui(){return ge()}async function di(){return Se()}function fi(e){return e?C.generatingSessionIds.has(e)||C.pendingCallApiSessionIds.has(e)?{ok:!1,reason:`running`}:fr(e)>0?{ok:!1,reason:`queued`}:{ok:!0}:{ok:!1,reason:`missing`}}async function pi(e){let t=fi(e);return t.ok?await ye(e)?(C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await Qr(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))),{ok:!0}):{ok:!1,reason:`missing`}:t}async function mi(e){return Ee(e)}async function hi(e){return si(e)}async function gi(e){return me(e)}async function _i(e,t){return xe(e,t)}async function vi(e,t=null){return be(e,t)}n(`zh`,{toolPanel:{agentRestrictedBanner:`当前 Agent 限制了可用工具,部分工具已禁用`,noMatch:`没有匹配的工具`,enabledCount:`已启用 {enabled}/{total} 个工具`,toolsEnabled:`工具已启用`,allToolsDisabled:`所有工具已禁用`,toggleBtnEnabled:`禁用所有工具`,toggleBtnDisabled:`启用所有工具`,mcpServiceToolCount:`{count} 个工具`,mcpServiceExpand:`展开/收起工具列表`,mcpExcludedByAgent:`已被当前助手排除,可在助手编辑中调整`,categorySelectAllHint:`对该分类下可见项全选/取消全选`,stateOn:`已开启`,stateOff:`已关闭`,stateLine:`{name}:{state}`}}),n(`en`,{toolPanel:{agentRestrictedBanner:`Current agent has restricted available tools, some tools are disabled`,noMatch:`No matching tools`,enabledCount:`{enabled}/{total} tools enabled`,toolsEnabled:`Tools enabled`,allToolsDisabled:`All tools disabled`,toggleBtnEnabled:`Disable all tools`,toggleBtnDisabled:`Enable all tools`,mcpServiceToolCount:`{count} tools`,mcpServiceExpand:`Show/hide tool list`,mcpExcludedByAgent:`Excluded by current assistant; adjust in assistant editor`,categorySelectAllHint:`Select/deselect all visible items in this category`,stateOn:`On`,stateOff:`Off`,stateLine:`{name}: {state}`}});var yi=[],bi=[];function xi(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function Si(e){if(!e)return``;let t=e.description||``;if(t.startsWith(`[MCP:`)){let e=t.indexOf(`]`);e!==-1&&(t=t.slice(e+1).trim())}return t===(e.name||``)?``:t}async function Ci(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return yi=e.tools,yi}catch{}try{return yi=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],yi}catch{return yi=[],[]}}async function wi(){try{bi=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{bi=[]}return bi}async function Ti(){let e=`agentMcpClosedServers_${C.activeAgentId||`default`}`;try{C.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}catch{C.mcpClosedServers=[]}try{let{getAgent:e}=await A(async()=>{let{getAgent:e}=await import(`./agent-store-CE4-QMOA.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3])),t=C.activeAgentId?await e(C.activeAgentId):null;C.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null}catch{}}var Ei=!1,Di=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{Ei=e.enableToolPreselect===!0,Di=e.toolConfirmationEnabled!==!1,$i()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&(yi=e.mcpTools.newValue||[],i.debug(`[SidePanel] MCP toolcache updated:`,yi.length,``),n=!0),e.ragTools&&(bi=e.ragTools.newValue||[],i.debug(`[SidePanel] RAG toolcache updated:`,bi.length),n=!0),e.mcpEnabled&&(Oi=e.mcpEnabled.newValue===!0,i.debug(`[SidePanel] MCP globaltoggle changed:`,Oi),n=!0),e.skillsEnabled&&(ki=e.skillsEnabled.newValue!==!1,i.debug(`[SidePanel] Skill global toggle changed:`,ki),n=!0),e.enableImageInput&&(Ai=e.enableImageInput.newValue===!0,i.debug(`[SidePanel] 图片识别全局开关变更:`,Ai),n=!0);let r=!1;e.enableToolPreselect&&(Ei=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(Di=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&$i(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Ji(),Yi(),Bi()),Qi())}),Ci().then(()=>Qi()),wi().then(()=>Qi());var Oi=!1,ki=!0,Ai=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{Oi=e.mcpEnabled===!0,ki=e.skillsEnabled!==!1,Ai=e.enableImageInput===!0,Qi()});function ji(){let e=[...f,...bi],t=C.activeAgentToolIds,n=e;if(t!=null){let r=new Set(t);n=e.filter(e=>r.has(e.id))}return ki||(n=n.filter(e=>e.id!==`agent_skill`)),C.agentPlatform?.connected!==!0&&(n=n.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),Ai||(n=n.filter(e=>e.id!==`read_image`)),n}function Mi(){if(!Oi||C.agentPlatform?.connected!==!0)return[];let e=new Map;return yi.forEach(t=>{let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[],toolCount:0});let r=e.get(n);r.tools.push(t),r.toolCount++}),Array.from(e.values())}function Ni(e){return Array.isArray(C.mcpClosedServers)&&C.mcpClosedServers.includes(e)}function Pi(e){return Array.isArray(C.activeAgentMcpExcludedServerIds)&&C.activeAgentMcpExcludedServerIds.includes(e)}function Fi(e){return!Ni(e)&&!Pi(e)}function Ii(){if(C.currentCategory!==`all`&&C.currentCategory!==`mcp`)return[];let e=Mi();if(C.currentSearch){let t=C.currentSearch;e=e.filter(e=>(e.serverName||``).toLowerCase().includes(t)||(e.serverId||``).toLowerCase().includes(t)||e.tools.some(e=>(e.name||``).toLowerCase().includes(t)||xi(e).toLowerCase().includes(t)))}return e}function Li(e,t){Array.isArray(C.mcpClosedServers)||(C.mcpClosedServers=[]);let n=C.mcpClosedServers.indexOf(e);t?n>-1&&C.mcpClosedServers.splice(n,1):n===-1&&C.mcpClosedServers.push(e)}async function Ri(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;C.currentCategory=`all`,C.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await Ci(),await wi(),await Ti(),Ji(),Yi(),chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{let t=document.getElementById(`toolsPreselectToggle`);t&&(t.checked=e.enableToolPreselect===void 0?!1:e.enableToolPreselect);let n=document.getElementById(`toolConfirmToggle`);n&&(n.checked=e.toolConfirmationEnabled===void 0?!0:e.toolConfirmationEnabled)}),document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),Bi(),e.classList.add(`show`),i.debug(`[SidePanel] opentool popup`)}function zi(){let e=document.getElementById(`toolsPopupOverlay`);e&&(document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.style.background=``,e.style.color=``,e.style.borderColor=``}),e.classList.remove(`show`),i.debug(`[SidePanel] closetool popup`))}function Bi(){let e=document.getElementById(`toolsPopupList`);if(!e)return;e.innerHTML=``;let t=ji();if(C.activeAgentToolIds!==null&&C.activeAgentToolIds!==void 0){let t=document.createElement(`div`);t.className=`popup-tool-agent-banner`,t.innerHTML=`<span>${r(`toolPanel.agentRestrictedBanner`)}</span>`,e.appendChild(t)}let n={};t.forEach(e=>{if(C.currentCategory!==`all`&&e.category!==C.currentCategory)return;if(C.currentSearch){let t=e.name.toLowerCase().includes(C.currentSearch),n=xi(e).toLowerCase().includes(C.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=Ii();if(Zt.forEach(a=>{let o=a===`mcp`,s=n[a]||[],c=o?i:[];if(o?c.length===0:s.length===0)return;let l;if(o)l=`${c.filter(e=>Fi(e.serverId)).length}/${c.length}`;else{let e=t.filter(e=>e.category===a);l=`${e.filter(e=>C.enabledTools.includes(e.id)).length}/${e.length}`}let u=document.createElement(`div`);u.className=`popup-tool-category-group`,u.dataset.category=a;let d=document.createElement(`div`);d.className=`popup-tool-category`,d.dataset.category=a;let f=C.collapsedCategories[a]||!1;d.innerHTML=`
|
|
30
30
|
<span class="category-expand-icon">${f?`▶`:`▼`}</span>
|
|
31
31
|
<span class="category-name">${r(`toolCategory.`+a)}</span>
|
|
32
32
|
<span class="category-count">${l}</span>
|
|
33
|
-
<button type="button" class="category-select-all" title="${
|
|
33
|
+
<button type="button" class="category-select-all" title="${Me(r(`toolPanel.categorySelectAllHint`))}"></button>
|
|
34
34
|
`,d.addEventListener(`click`,e=>{if(e.target.closest(`.category-select-all`)){e.stopPropagation(),Ui(a);return}Hi(a)}),u.appendChild(d);let p=document.createElement(`div`);p.className=`popup-tool-items ${f?`collapsed`:``}`,(o?c:s).forEach(e=>{if(o){p.appendChild(Vi(e,a));return}let t=C.enabledTools.includes(e.id),n=document.createElement(`div`);n.className=`popup-tool-item`,n.dataset.category=a;let r=xi(e);n.innerHTML=`
|
|
35
35
|
<input type="checkbox" id="tool_${e.id}" ${t?`checked`:``}>
|
|
36
36
|
<div class="popup-tool-content">
|
|
37
|
-
<div class="popup-tool-name" title="${
|
|
38
|
-
<div class="popup-tool-desc" title="${
|
|
37
|
+
<div class="popup-tool-name" title="${Me(e.name)}">${I(e.name)}</div>
|
|
38
|
+
<div class="popup-tool-desc" title="${Me(r)}">${I(r)}</div>
|
|
39
39
|
</div>
|
|
40
40
|
`;let i=n.querySelector(`input[type="checkbox"]`);i&&i.addEventListener(`change`,t=>{if(t.stopPropagation(),t.target.checked)C.enabledTools.includes(e.id)||C.enabledTools.push(e.id);else{let t=C.enabledTools.indexOf(e.id);t>-1&&C.enabledTools.splice(t,1)}Gi(a),Ji(),Yi(),Wi(a)}),p.appendChild(n)}),u.appendChild(p),e.appendChild(u),Wi(a)}),e.children.length===0){let t=document.createElement(`div`);t.className=`popup-tool-empty`,t.textContent=r(`toolPanel.noMatch`),e.appendChild(t)}}function Vi(e,t){let n=Pi(e.serverId),i=!Ni(e.serverId),a=document.createElement(`div`);a.className=`popup-mcp-service-block`,a.dataset.category=t,a.dataset.serverId=e.serverId;let o=document.createElement(`div`);o.className=`popup-tool-item popup-mcp-service-item`,o.innerHTML=`
|
|
41
|
-
<input type="checkbox" id="mcpsvc_${
|
|
41
|
+
<input type="checkbox" id="mcpsvc_${Me(e.serverId)}" ${i?`checked`:``} ${n?`disabled`:``}>
|
|
42
42
|
<div class="popup-tool-content">
|
|
43
|
-
<div class="popup-tool-name" title="${
|
|
44
|
-
<span class="popup-mcp-service-name">${
|
|
43
|
+
<div class="popup-tool-name" title="${Me(e.serverName)}">
|
|
44
|
+
<span class="popup-mcp-service-name">${I(e.serverName)}</span>
|
|
45
45
|
<span class="popup-mcp-service-count">${r(`toolPanel.mcpServiceToolCount`,{count:e.toolCount})}</span>
|
|
46
46
|
</div>
|
|
47
47
|
<div class="popup-tool-desc popup-mcp-service-meta">
|
|
48
|
-
<span class="popup-mcp-service-id" title="ID: ${
|
|
48
|
+
<span class="popup-mcp-service-id" title="ID: ${Me(e.serverId)}">ID: ${I(e.serverId)}</span>
|
|
49
49
|
</div>
|
|
50
50
|
${n?`<div class="popup-tool-desc popup-mcp-service-hint">${r(`toolPanel.mcpExcludedByAgent`)}</div>`:``}
|
|
51
51
|
</div>
|
|
52
52
|
<button type="button" class="popup-mcp-expand-btn" title="${r(`toolPanel.mcpServiceExpand`)}">▶</button>
|
|
53
|
-
`,a.appendChild(o);let s=document.createElement(`div`);s.className=`popup-mcp-tool-list collapsed`,e.tools.forEach(e=>{let t=e.name||``,n=Si(e),r=document.createElement(`div`);r.className=`popup-mcp-tool-row`,r.title=n?`${t}:${n}`:t,r.innerHTML=`<span class="popup-mcp-tool-name">${
|
|
54
|
-
`)}function ea(e,t,n){let r=Array.isArray(e)?e:[];if(n===!0||!Array.isArray(t)||t.length===0)return{tools:r,migrated:!1};let i=[...r];for(let e of t)i.includes(e.id)||i.push(e.id);return{tools:i,migrated:i.length!==r.length}}function ta(e=[]){let t=Array.isArray(e)?e:[];return new Set([...f.map(e=>e.id),...Xt,...t.map(e=>e.id)])}function na(){document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Ji(),Yi(),Bi()),Qi()}n(`zh`,{agentToolFilter:{selectedCountHint:`已勾选 {count} 项`}}),n(`en`,{agentToolFilter:{selectedCountHint:`{count} selected`}});function ra(e,{query:t,selectedOnly:n,selectedSet:r,getDesc:i}){if(n&&!r.has(e.id))return!1;let a=String(t||``).toLowerCase();return!a||(e.name||``).toLowerCase().includes(a)?!0:String((i?i(e):e.description)||``).toLowerCase().includes(a)}function ia(e,{query:t,selectedOnly:n,excludedSet:r,getDesc:i}){if(n&&r.has(e.serverId))return!1;let a=String(t||``).toLowerCase();return!a||[e.serverName,e.serverId].filter(Boolean).join(` `).toLowerCase().includes(a)?!0:(e.tools||[]).some(e=>(e.name||``).toLowerCase().includes(a)?!0:String((i?i(e):e.description)||``).toLowerCase().includes(a))}function aa({tools:e,services:t,selectedSet:n,excludedSet:r,query:i,selectedOnly:a,getDesc:o}){let s={query:String(i||``).trim().toLowerCase(),selectedOnly:a===!0,selectedSet:n,excludedSet:r,getDesc:o};return{tools:(e||[]).filter(e=>ra(e,s)),services:(t||[]).filter(e=>ia(e,s))}}var oa={CONFIRM:`confirm`,CLARIFY:`clarify`},sa=new Map,ca=null,la=[];function ua(e,t){sa.set(e,t)}function da(e){if(ca===e){ma(e)||(ca=null,pa());return}if(ca===null){ca=e,ma(e)||(ca=null,pa());return}la.includes(e)||la.push(e),i.debug(`[SidePanel] interaction ${e} queued behind ${ca}`)}function fa(e){ca===e&&(ca=null,pa())}function pa(){for(;la.length>0;){let e=la.shift();if(ca=e,ma(e))return;ca=null}}function ma(e){let t=sa.get(e);if(!t||typeof t.present!=`function`)return!1;try{return t.present()===!0}catch(t){return i.error(`[SidePanel] present ${e} failed:`,t?.message),!1}}function ha(e){if(!ca||ca===e)return;let t=sa.get(ca);if(!(!t||typeof t.refresh!=`function`))try{t.refresh()}catch(t){i.error(`[SidePanel] refresh ${ca} hint for ${e} change failed:`,t?.message)}}function ga(e){let t=0;for(let[n,r]of sa){if(n===e)continue;let i=typeof r.pendingCount==`function`?r.pendingCount():0;t+=Number.isFinite(i)&&i>0?i:0}return t}function _a(e,t){if(!t||!t.toolCallId)return;let n={type:`INTERACTION_DISPLAYED`,data:{kind:e,toolCallId:t.toolCallId,sessionId:t.sessionId||null}};Promise.resolve(chrome.runtime.sendMessage(n)).catch(t=>{i.debug(`[SidePanel] report ${e} displayed failed:`,t?.message)})}var va=oa.CLARIFY;n(`zh`,{clarify:{remainingTimeDynamic:`剩余时间: {time}`,timeoutSoon:`时间即将耗尽`,sessionNameTitle:`{title}`,sessionNameId:`会话 ID: {id}`,recommended:`推荐`,otherOption:`其他(自定义输入)`,timedOut:`已超时`,timedOutDefaulted:`已超时,已按推荐项「{option}」继续`,dropped:`澄清弹窗无法显示,已按未澄清继续`,extend:`延长时间`,extended:`已延长倒计时`,extendLimit:`已达延长上限`}}),n(`en`,{clarify:{remainingTimeDynamic:`Remaining time: {time}`,timeoutSoon:`Time is almost up`,sessionNameTitle:`{title}`,sessionNameId:`Session ID: {id}`,recommended:`Recommended`,otherOption:`Other (custom input)`,timedOut:`Timed out`,timedOutDefaulted:`Timed out — continued with the recommended option "{option}"`,dropped:`Clarification dialog could not be shown; continuing as unanswered`,extend:`Extend time`,extended:`Countdown extended`,extendLimit:`Extend limit reached`}});var ya=[],z=null,ba=null,xa=!1;function Sa(e){return`${Math.floor(e/60)}:${(e%60).toString().padStart(2,`0`)}`}function Ca(e=`default`){try{let t=new(window.AudioContext||window.webkitAudioContext),n=t.createOscillator(),r=t.createGain();n.connect(r),r.connect(t.destination);let a={default:{frequency:800,duration:.3},success:{frequency:523,duration:.2},warning:{frequency:440,duration:.4},error:{frequency:220,duration:.5}},o=a[e]||a.default;n.frequency.value=o.frequency,n.type=`sine`,r.gain.setValueAtTime(.3,t.currentTime),r.gain.exponentialRampToValueAtTime(.01,t.currentTime+o.duration),n.start(t.currentTime),n.stop(t.currentTime+o.duration),i.debug(`[SidePanel] soundplay:`,e)}catch(e){i.error(`[SidePanel] play sound failed:`,e.message)}}function wa(e,t){let n=document.getElementById(`clarifyTimer`),i=document.getElementById(`clarifyTimerText`);if(!n||!i)return;i.textContent=r(`clarify.remainingTimeDynamic`,{time:Sa(e)});let a=e/t*100,o=document.getElementById(`clarifyTimerBarFill`);o&&(o.style.width=`${Math.max(0,Math.min(100,a))}%`),n.classList.remove(`warning`,`critical`),e<=10?(n.classList.add(`critical`),i.textContent=r(`clarify.timeoutSoon`,{time:Sa(e)})):(e<=30||a<=15)&&n.classList.add(`warning`);let s=document.getElementById(`clarifyExtendBtn`);s&&s.classList.toggle(`show`,e<=60||a<=50),e===30&&Ca(`warning`)}function Ta(e){Ea(),C.clarifyTimeoutValue=e;let t=Math.ceil(e/1e3),n=t;wa(n,t),C.clarifyTimerInterval=setInterval(()=>{n--,n<=0?(Ea(),z&&_a(va,z)):wa(n,t)},1e3)}function Ea(){C.clarifyTimerInterval&&=(clearInterval(C.clarifyTimerInterval),null)}function Da(){let e=document.getElementById(`clarifyExtendBtn`);if(!e)return;let t=ba===0;e.disabled=t||xa,e.textContent=r(t?`clarify.extendLimit`:`clarify.extend`)}function Oa(){!z||xa||ba!==0&&(xa=!0,Da(),Promise.resolve(chrome.runtime.sendMessage({type:`CLARIFY_EXTEND`,toolCallId:z.toolCallId,sessionId:z.sessionId})).catch(e=>{i.debug(`[SidePanel] send clarify extend failed:`,e?.message)}),setTimeout(()=>{xa&&(xa=!1,Da())},3e3))}function ka(e){let t=e?.toolCallId;if(!(!z||z.toolCallId!==t)){if(xa=!1,e.denied||typeof e.remainingMs!=`number`){ba=0,Da(),
|
|
53
|
+
`,a.appendChild(o);let s=document.createElement(`div`);s.className=`popup-mcp-tool-list collapsed`,e.tools.forEach(e=>{let t=e.name||``,n=Si(e),r=document.createElement(`div`);r.className=`popup-mcp-tool-row`,r.title=n?`${t}:${n}`:t,r.innerHTML=`<span class="popup-mcp-tool-name">${I(t)}</span>`+(n?`<span class="popup-mcp-tool-desc">${I(n)}</span>`:``),s.appendChild(r)}),a.appendChild(s);let c=o.querySelector(`.popup-mcp-expand-btn`),l=()=>{let e=s.classList.toggle(`collapsed`);c&&(c.textContent=e?`▶`:`▼`)};c&&c.addEventListener(`click`,e=>{e.stopPropagation(),l()}),o.addEventListener(`click`,e=>{e.target.closest(`input[type="checkbox"]`)||e.target.closest(`.popup-mcp-expand-btn`)||l()});let u=o.querySelector(`input[type="checkbox"]`);return u&&u.addEventListener(`change`,t=>{t.stopPropagation(),Li(e.serverId,t.target.checked),Gi(`mcp`),Ji(),Yi(),Wi(`mcp`)}),a}function Hi(e){C.collapsedCategories[e]=!C.collapsedCategories[e];let t=document.querySelector(`.popup-tool-category-group[data-category="${e}"]`);if(!t)return;let n=t.querySelector(`.popup-tool-category`).querySelector(`.category-expand-icon`),r=t.querySelector(`.popup-tool-items`);C.collapsedCategories[e]?(n.textContent=`▶`,r.classList.add(`collapsed`)):(n.textContent=`▼`,r.classList.remove(`collapsed`))}function Ui(e){let t=document.querySelector(`.popup-tool-category-group[data-category="${e}"]`);if(!t)return;let n=Array.from(t.querySelectorAll(`.popup-tool-items input[type="checkbox"]:not(:disabled)`));if(n.length===0)return;let r=!n.every(e=>e.checked);n.forEach(e=>{e.checked!==r&&(e.checked=r,e.dispatchEvent(new Event(`change`)))}),Wi(e)}function Wi(e){let t=document.querySelector(`.popup-tool-category-group[data-category="${e}"]`),n=t?t.querySelector(`.category-select-all`):null;if(!n)return;let i=Array.from(t.querySelectorAll(`.popup-tool-items input[type="checkbox"]:not(:disabled)`));if(i.length===0){n.style.display=`none`;return}n.style.display=``,n.textContent=i.every(e=>e.checked)?r(`common.deselectAll`):r(`common.selectAll`)}function Gi(e){let t=document.querySelector(`.popup-tool-category[data-category="${e}"]`);if(!t)return;let n=t.querySelector(`.category-count`);if(!n)return;let r=0,i=0;if(e===`mcp`){let e=Ii();i=e.length,e.forEach(e=>{if(Pi(e.serverId))return;let t=document.getElementById(`mcpsvc_`+e.serverId);(t?t.checked:!Ni(e.serverId))&&r++})}else{let t=e===`knowledge`?bi:f.filter(t=>t.category===e);i=t.length,t.forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&t.checked&&r++})}n.textContent=`${r}/${i}`}function Ki(){return ji().filter(e=>{if(C.currentCategory!==`all`&&e.category!==C.currentCategory)return!1;if(C.currentSearch){let t=e.name.toLowerCase().includes(C.currentSearch.toLowerCase()),n=xi(e).toLowerCase().includes(C.currentSearch.toLowerCase());if(!t&&!n)return!1}return!0})}function qi(){Zt.forEach(e=>{Gi(e),Wi(e)})}function Ji(){let e=[`all`,...Zt],t=ji(),n=Mi(),r=n.filter(e=>Fi(e.serverId)).length,i=new Set(t.map(e=>e.id)),a=C.enabledTools.filter(e=>i.has(e)).length;e.forEach(e=>{let i=document.getElementById(`badge-`+e);if(!i)return;let o=0,s=0;if(e===`all`)o=t.length+n.length,s=a+r;else if(e===`mcp`)o=n.length,s=r;else{let n=t.filter(t=>t.category===e);o=n.length,s=n.filter(e=>C.enabledTools.includes(e.id)).length}i.textContent=`${s}/${o}`,e!==`all`&&i.parentElement&&(i.parentElement.style.display=o===0?`none`:``)})}function Yi(){let e=document.getElementById(`toolsEnabledCount`);if(!e)return;let t=ji(),n=new Set(t.map(e=>e.id)),i=C.enabledTools.filter(e=>n.has(e)).length,a=Mi(),o=a.filter(e=>Fi(e.serverId)).length;e.textContent=r(`toolPanel.enabledCount`,{enabled:i+o,total:t.length+a.length})}function Xi(){let e=[];[...ta(bi)].forEach(t=>{let n=document.getElementById(`tool_`+t);n?n.checked&&e.push(t):C.enabledTools.includes(t)&&e.push(t)}),C.enabledTools=e,typeof document<`u`&&document.dispatchEvent(new CustomEvent(`agent-tools-changed`));let t=Mi(),n=new Set(t.map(e=>e.serverId)),a=(C.mcpClosedServers||[]).filter(e=>!n.has(e)),o=0;t.forEach(e=>{if(Pi(e.serverId)){Ni(e.serverId)&&a.push(e.serverId);return}let t=document.getElementById(`mcpsvc_`+e.serverId);(t?t.checked:!Ni(e.serverId))?o++:a.push(e.serverId)}),C.mcpClosedServers=a;let s=`agentEnabledTools_${C.activeAgentId||`default`}`,c=`agentMcpClosedServers_${C.activeAgentId||`default`}`;chrome.storage.local.set({[s]:C.enabledTools,[c]:C.mcpClosedServers},()=>{i.debug(`[SidePanel] tool configurationsavedto agent:`,s,C.enabledTools,c,C.mcpClosedServers)}),ni().catch(()=>{});let l=document.getElementById(`toolsPreselectToggle`);l&&chrome.storage.local.set({enableToolPreselect:l.checked},()=>{i.debug(`[SidePanel] toolpre-filter toggle saved:`,l.checked)});let u=document.getElementById(`toolConfirmToggle`);u&&chrome.storage.local.set({toolConfirmationEnabled:u.checked},()=>{i.debug(`[SidePanel] sensitive-operation confirmation toggle saved:`,u.checked)}),Qi();let d=ji(),f=new Set(d.map(e=>e.id)),p=C.enabledTools.filter(e=>f.has(e)).length+o;P(p>0?r(`toolPanel.toolsEnabled`,{count:p}):r(`toolPanel.allToolsDisabled`),`success`)}function Zi(e){Ii().forEach(t=>{if(Pi(t.serverId))return;let n=document.getElementById(`mcpsvc_`+t.serverId);n&&(n.checked=e),Li(t.serverId,e)})}function Qi(){if(typeof document>`u`)return;let e=document.getElementById(`toolsToggleBtn`),t=document.getElementById(`toolsBadge`),n=ji(),i=new Set(n.map(e=>e.id)),a=C.enabledTools.filter(e=>i.has(e)).length+Mi().filter(e=>Fi(e.serverId)).length;e&&(C.useTools&&a>0?(e.classList.add(`active`),e.title=r(`toolPanel.toggleBtnEnabled`,{count:a})):(e.classList.remove(`active`),e.title=r(`toolPanel.toggleBtnDisabled`))),t&&(a>0?(t.textContent=a,t.style.display=`inline`):t.style.display=`none`);let o=document.getElementById(`toolsConfigCount`);o&&(o.textContent=a);let s=document.getElementById(`toolsConfigBtn`);s&&s.classList.toggle(`active`,C.useTools&&a>0)}function $i(){let e=document.getElementById(`toolsConfigBtn`);if(!e)return;let t=document.getElementById(`toolsConfigFlagPreselect`),n=document.getElementById(`toolsConfigFlagConfirm`);t&&t.classList.toggle(`on`,Ei),n&&n.classList.toggle(`on`,Di);let i=(e,t)=>r(`toolPanel.stateLine`,{name:e,state:r(t?`toolPanel.stateOn`:`toolPanel.stateOff`)});e.title=[r(`toolPanel.configBtnTitle`),i(r(`toolPanel.preselect`),Ei),i(r(`react.toolConfirmation`),Di)].join(`
|
|
54
|
+
`)}function ea(e,t,n){let r=Array.isArray(e)?e:[];if(n===!0||!Array.isArray(t)||t.length===0)return{tools:r,migrated:!1};let i=[...r];for(let e of t)i.includes(e.id)||i.push(e.id);return{tools:i,migrated:i.length!==r.length}}function ta(e=[]){let t=Array.isArray(e)?e:[];return new Set([...f.map(e=>e.id),...Xt,...t.map(e=>e.id)])}function na(){document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Ji(),Yi(),Bi()),Qi()}n(`zh`,{agentToolFilter:{selectedCountHint:`已勾选 {count} 项`}}),n(`en`,{agentToolFilter:{selectedCountHint:`{count} selected`}});function ra(e,{query:t,selectedOnly:n,selectedSet:r,getDesc:i}){if(n&&!r.has(e.id))return!1;let a=String(t||``).toLowerCase();return!a||(e.name||``).toLowerCase().includes(a)?!0:String((i?i(e):e.description)||``).toLowerCase().includes(a)}function ia(e,{query:t,selectedOnly:n,excludedSet:r,getDesc:i}){if(n&&r.has(e.serverId))return!1;let a=String(t||``).toLowerCase();return!a||[e.serverName,e.serverId].filter(Boolean).join(` `).toLowerCase().includes(a)?!0:(e.tools||[]).some(e=>(e.name||``).toLowerCase().includes(a)?!0:String((i?i(e):e.description)||``).toLowerCase().includes(a))}function aa({tools:e,services:t,selectedSet:n,excludedSet:r,query:i,selectedOnly:a,getDesc:o}){let s={query:String(i||``).trim().toLowerCase(),selectedOnly:a===!0,selectedSet:n,excludedSet:r,getDesc:o};return{tools:(e||[]).filter(e=>ra(e,s)),services:(t||[]).filter(e=>ia(e,s))}}var oa={CONFIRM:`confirm`,CLARIFY:`clarify`},sa=new Map,ca=null,la=[];function ua(e,t){sa.set(e,t)}function da(e){if(ca===e){ma(e)||(ca=null,pa());return}if(ca===null){ca=e,ma(e)||(ca=null,pa());return}la.includes(e)||la.push(e),i.debug(`[SidePanel] interaction ${e} queued behind ${ca}`)}function fa(e){ca===e&&(ca=null,pa())}function pa(){for(;la.length>0;){let e=la.shift();if(ca=e,ma(e))return;ca=null}}function ma(e){let t=sa.get(e);if(!t||typeof t.present!=`function`)return!1;try{return t.present()===!0}catch(t){return i.error(`[SidePanel] present ${e} failed:`,t?.message),!1}}function ha(e){if(!ca||ca===e)return;let t=sa.get(ca);if(!(!t||typeof t.refresh!=`function`))try{t.refresh()}catch(t){i.error(`[SidePanel] refresh ${ca} hint for ${e} change failed:`,t?.message)}}function ga(e){let t=0;for(let[n,r]of sa){if(n===e)continue;let i=typeof r.pendingCount==`function`?r.pendingCount():0;t+=Number.isFinite(i)&&i>0?i:0}return t}function _a(e,t){if(!t||!t.toolCallId)return;let n={type:`INTERACTION_DISPLAYED`,data:{kind:e,toolCallId:t.toolCallId,sessionId:t.sessionId||null}};Promise.resolve(chrome.runtime.sendMessage(n)).catch(t=>{i.debug(`[SidePanel] report ${e} displayed failed:`,t?.message)})}var va=oa.CLARIFY;n(`zh`,{clarify:{remainingTimeDynamic:`剩余时间: {time}`,timeoutSoon:`时间即将耗尽`,sessionNameTitle:`{title}`,sessionNameId:`会话 ID: {id}`,recommended:`推荐`,otherOption:`其他(自定义输入)`,timedOut:`已超时`,timedOutDefaulted:`已超时,已按推荐项「{option}」继续`,dropped:`澄清弹窗无法显示,已按未澄清继续`,extend:`延长时间`,extended:`已延长倒计时`,extendLimit:`已达延长上限`}}),n(`en`,{clarify:{remainingTimeDynamic:`Remaining time: {time}`,timeoutSoon:`Time is almost up`,sessionNameTitle:`{title}`,sessionNameId:`Session ID: {id}`,recommended:`Recommended`,otherOption:`Other (custom input)`,timedOut:`Timed out`,timedOutDefaulted:`Timed out — continued with the recommended option "{option}"`,dropped:`Clarification dialog could not be shown; continuing as unanswered`,extend:`Extend time`,extended:`Countdown extended`,extendLimit:`Extend limit reached`}});var ya=[],z=null,ba=null,xa=!1;function Sa(e){return`${Math.floor(e/60)}:${(e%60).toString().padStart(2,`0`)}`}function Ca(e=`default`){try{let t=new(window.AudioContext||window.webkitAudioContext),n=t.createOscillator(),r=t.createGain();n.connect(r),r.connect(t.destination);let a={default:{frequency:800,duration:.3},success:{frequency:523,duration:.2},warning:{frequency:440,duration:.4},error:{frequency:220,duration:.5}},o=a[e]||a.default;n.frequency.value=o.frequency,n.type=`sine`,r.gain.setValueAtTime(.3,t.currentTime),r.gain.exponentialRampToValueAtTime(.01,t.currentTime+o.duration),n.start(t.currentTime),n.stop(t.currentTime+o.duration),i.debug(`[SidePanel] soundplay:`,e)}catch(e){i.error(`[SidePanel] play sound failed:`,e.message)}}function wa(e,t){let n=document.getElementById(`clarifyTimer`),i=document.getElementById(`clarifyTimerText`);if(!n||!i)return;i.textContent=r(`clarify.remainingTimeDynamic`,{time:Sa(e)});let a=e/t*100,o=document.getElementById(`clarifyTimerBarFill`);o&&(o.style.width=`${Math.max(0,Math.min(100,a))}%`),n.classList.remove(`warning`,`critical`),e<=10?(n.classList.add(`critical`),i.textContent=r(`clarify.timeoutSoon`,{time:Sa(e)})):(e<=30||a<=15)&&n.classList.add(`warning`);let s=document.getElementById(`clarifyExtendBtn`);s&&s.classList.toggle(`show`,e<=60||a<=50),e===30&&Ca(`warning`)}function Ta(e){Ea(),C.clarifyTimeoutValue=e;let t=Math.ceil(e/1e3),n=t;wa(n,t),C.clarifyTimerInterval=setInterval(()=>{n--,n<=0?(Ea(),z&&_a(va,z)):wa(n,t)},1e3)}function Ea(){C.clarifyTimerInterval&&=(clearInterval(C.clarifyTimerInterval),null)}function Da(){let e=document.getElementById(`clarifyExtendBtn`);if(!e)return;let t=ba===0;e.disabled=t||xa,e.textContent=r(t?`clarify.extendLimit`:`clarify.extend`)}function Oa(){!z||xa||ba!==0&&(xa=!0,Da(),Promise.resolve(chrome.runtime.sendMessage({type:`CLARIFY_EXTEND`,toolCallId:z.toolCallId,sessionId:z.sessionId})).catch(e=>{i.debug(`[SidePanel] send clarify extend failed:`,e?.message)}),setTimeout(()=>{xa&&(xa=!1,Da())},3e3))}function ka(e){let t=e?.toolCallId;if(!(!z||z.toolCallId!==t)){if(xa=!1,e.denied||typeof e.remainingMs!=`number`){ba=0,Da(),P(r(`clarify.extendLimit`),`warning`);return}ba=typeof e.extendsLeft==`number`?e.extendsLeft:ba,Ta(e.remainingMs),Da(),P(r(`clarify.extended`),`success`),i.debug(`[SidePanel] clarify extended, remainingMs:`,e.remainingMs,`left:`,ba)}}function Aa(e){let t=ya.length,n=ga(va),i=e.question||``;return t>0&&(i+=` ${r(`dialog.pendingQueueClarify`,{count:t})}`),n>0&&(i+=` ${r(`dialog.otherPending`,{count:n})}`),i}function ja(){if(!z)return;let e=document.getElementById(`clarifyQuestion`);e&&(e.textContent=Aa(z))}function Ma(e){let{question:t,recommendedOption:n,allowCustomInput:a=!0,allowAdditionalInfo:o=!0,timeout:s=3e5,sessionId:c}=e,l=document.getElementById(`clarifyOverlay`);if(!l)return!1;let u=Array.isArray(e.options)?e.options:e.options?[String(e.options)]:[];C.currentClarifyToolCallId=e.toolCallId,C.currentClarifySessionId=c||null;let d=document.getElementById(`clarifySessionName`);if(d)if(c&&C.sessions){let e=C.sessions.find(e=>e.id===c);e?(d.textContent=r(`clarify.sessionNameTitle`,{title:e.title}),d.style.display=`block`,d.title=e.title||``):(d.textContent=r(`clarify.sessionNameId`,{id:c.substring(0,8)}),d.style.display=`block`,d.title=c)}else d.textContent=``,d.title=``,d.style.display=`none`;let f=n!==void 0&&n>=0?n:0,p=[f],m=f,h=document.getElementById(`clarifyQuestion`);h&&(h.textContent=Aa(e));let g=document.getElementById(`clarifyOptionsList`);if(g&&(document.querySelectorAll(`.clarify-option-item`).forEach(e=>{e.remove()}),u.forEach((e,t)=>{let n=p.includes(t),i=document.createElement(`div`);i.className=`clarify-option-item ${m===t?`selected`:``} ${n?`recommended`:``}`,i.dataset.index=t,i.setAttribute(`role`,`radio`),i.setAttribute(`aria-checked`,m===t?`true`:`false`),i.setAttribute(`tabindex`,m===t?`0`:`-1`),i.innerHTML=`
|
|
55
55
|
<div class="clarify-option-radio"></div>
|
|
56
56
|
<div class="clarify-option-content">${e}${n?`<span class="clarify-option-badge">${r(`clarify.recommended`)}</span>`:``}</div>
|
|
57
57
|
`,i.addEventListener(`click`,()=>Va(t)),g.appendChild(i)}),a)){let e=document.createElement(`div`);e.className=`clarify-option-item`,e.dataset.index=-1,e.setAttribute(`role`,`radio`),e.setAttribute(`aria-checked`,`false`),e.setAttribute(`tabindex`,`-1`),e.innerHTML=`
|
|
58
58
|
<div class="clarify-option-radio"></div>
|
|
59
59
|
<div class="clarify-option-content clarify-option-other">${r(`clarify.otherOption`)}</div>
|
|
60
|
-
`,e.addEventListener(`click`,()=>Va(-1)),g.appendChild(e);let t=document.getElementById(`clarifyCustomInput`);t&&g.appendChild(t)}let _=document.getElementById(`clarifyCustomInput`);_&&_.classList.remove(`show`);let v=document.getElementById(`clarifyAdditionalInfo`);v&&v.classList.toggle(`show`,o);let y=document.getElementById(`clarifyCustomTextarea`);y&&(y.value=``);let b=document.getElementById(`clarifyAdditionalTextarea`);b&&(b.value=``),l.classList.add(`show`);let x=document.querySelector(`#clarifyContainer .clarify-content`),S=document.querySelector(`#clarifyContainer .clarify-header`);return x&&(x.scrollTop=0),S&&S.classList.remove(`scrolled`),ba=null,xa=!1,Da(),Ta(s),i.debug(`[SidePanel] clarification dialogshown:`,e.toolCallId,t),!0}function Na(){if(z)return!0;if(ya.length===0)return!1;let e=ya.shift();return Ma(e)?(z=e,_a(va,e),!0):(i.error(`[SidePanel] clarify overlay missing, settle as unanswered:`,e.toolCallId),Pa(e),F(r(`clarify.dropped`),`warning`),!1)}function Pa(e){Promise.resolve(chrome.runtime.sendMessage({type:`CLARIFY_RESPONSE`,toolCallId:e.toolCallId,selectedOption:-1,customInput:``,additionalInfo:``})).catch(e=>{i.debug(`[SidePanel] send unanswered clarify response failed:`,e?.message)})}function Fa(){if(ya.length>0){da(va);return}Ia(),fa(va)}function Ia(){let e=document.getElementById(`clarifyOverlay`);e&&e.classList.remove(`show`),C.currentClarifyToolCallId=null,C.currentClarifySessionId=null,Ea()}function La(){z=null,Fa()}function Ra(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&e.question===t.question}function za(e){let t={...e,sessionId:e.sessionId||null};if(i.debug(`[SidePanel] showclarification dialog:`,t.toolCallId,e),z&&Ra(z,t)){i.debug(`[SidePanel] duplicate clarify request, ignored:`,t.toolCallId);return}if(ya.some(e=>Ra(e,t))){i.debug(`[SidePanel] queued duplicate clarify, ignored:`,t.toolCallId);return}ya.push(t),da(va),ja(),ha(va)}function Ba(){if(z){La();return}Ia()}function Va(e){document.querySelectorAll(`.clarify-option-item`).forEach(e=>{e.classList.remove(`selected`),e.setAttribute(`aria-checked`,`false`),e.setAttribute(`tabindex`,`-1`)});let t=document.querySelector(`.clarify-option-item[data-index="${e}"]`);t&&(t.classList.add(`selected`),t.setAttribute(`aria-checked`,`true`),t.setAttribute(`tabindex`,`0`));let n=document.getElementById(`clarifyCustomInput`);if(n)if(e===-1){n.classList.add(`show`);let e=document.getElementById(`clarifyCustomTextarea`);e&&e.focus()}else n.classList.remove(`show`);i.debug(`[SidePanel] selectclarificationselect :`,e)}function Ha(){if(!z){i.error(`[SidePanel] no has currenttool callID`);return}let e=z.toolCallId,t=z.sessionId,n=-1;document.querySelectorAll(`.clarify-option-item`).forEach((e,t)=>{e.classList.contains(`selected`)&&(n=parseInt(e.dataset.index))});let r=document.getElementById(`clarifyCustomTextarea`),a=r?r.value.trim():``,o=document.getElementById(`clarifyAdditionalTextarea`),s=o?o.value.trim():``,c={type:`CLARIFY_RESPONSE`,toolCallId:e,sessionId:t,selectedOption:n,customInput:a,additionalInfo:s};i.debug(`[SidePanel] send clarificationresponse:`,c),chrome.runtime.sendMessage(c),La()}function Ua(){if(z){let e={type:`CLARIFY_RESPONSE`,toolCallId:z.toolCallId,sessionId:z.sessionId,selectedOption:-1,customInput:``,additionalInfo:``};chrome.runtime.sendMessage(e)}Ba()}function Wa(e){return e?.reason===`timeout`&&e?.defaultOption||null}function Ga(e){i.debug(`[SidePanel] received clarificationtimeoutnotification:`,e);let t=e?.toolCallId;if(!t){if(e?.sessionId&&C.currentClarifySessionId&&e.sessionId!==C.currentClarifySessionId){i.debug(`[SidePanel] clarificationtimeoutfrom othersession,ignore`);return}if(!z)return;Ka(Wa(e));return}if(z&&z.toolCallId===t){Ka(Wa(e));return}let n=ya.findIndex(e=>e.toolCallId===t);n>=0&&(i.debug(`[SidePanel] drop queued clarify (already settled by background):`,t),ya.splice(n,1),ja(),ha(va))}function Ka(e=null){let t=z?.question;La(),F(e?r(`clarify.timedOutDefaulted`,{option:e}):`${r(`clarify.timedOut`)}${t?`:${t}`:``}`,`warning`),Ca(`error`)}ua(va,{present:Na,pendingCount:()=>ya.length,refresh:ja});function qa(){let e=document.getElementById(`clarifyConfirmBtn`);e&&e.addEventListener(`click`,Ha);let t=document.getElementById(`clarifyCancelBtn`);t&&t.addEventListener(`click`,Ua);let n=document.getElementById(`clarifyExtendBtn`);n&&n.addEventListener(`click`,Oa);let r=document.querySelector(`#clarifyContainer .clarify-content`),a=document.querySelector(`#clarifyContainer .clarify-header`);r&&a&&r.addEventListener(`scroll`,()=>{a.classList.toggle(`scrolled`,r.scrollTop>2)}),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_CLARIFY_DIALOG`?(i.debug(`[SidePanel] received clarificationrequested :`,e,`currently activesession:`,C.activeSessionId),za(e.data),n({success:!0})):e.type===`PLAY_NOTIFICATION_SOUND`?(i.debug(`[SidePanel] recei to play soundrequested :`,e),Ca(e.soundType),n({success:!0})):e.type===`CLARIFY_TIMEOUT`?Ga(e):e.type===`CLARIFY_EXTENDED`&&ka(e)}),i.debug(`[SidePanel] clarification dialogeventinitializing`)}var Ja=oa.CONFIRM,Ya=[],Xa=null,Za=null,Qa=null;function $a(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}function eo(){Za&&=(clearInterval(Za),null),Qa&&=(clearTimeout(Qa),null)}function to(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&JSON.stringify(e.args??null)===JSON.stringify(t.args??null)}function no(e){let t=e.message||r(`dialog.confirmAction`,{name:e.toolLabel||e.toolName}),n=Ya.length,i=ga(Ja),a=t;return n>0&&(a+=` ${r(`dialog.pendingQueue`,{count:n})}`),i>0&&(a+=` ${r(`dialog.otherPending`,{count:i})}`),a}function ro(e){let{toolName:t,toolLabel:n,args:a,timeout:o=3e5}=e;C.currentConfirmToolCallId=e.toolCallId,C.currentConfirmSessionId=e.sessionId||null;let s=document.getElementById(`confirmOverlay`);if(!s)return!1;document.getElementById(`confirmToolName`).textContent=n||t;let c=e.variant===`network`,l=document.getElementById(`confirmTitle`);l&&(l.textContent=r(c?`dialog.networkTitle`:`dialog.operationConfirm`));let u=document.getElementById(`confirmApproveLoopBtn`);u&&(u.textContent=r(c?`dialog.approveWhitelist`:`dialog.approveLoop`));let d=document.getElementById(`confirmArgsSummary`);if(d&&a){let e=Object.entries(a).filter(([e,t])=>t!=null&&t!==``).slice(0,5);e.length>0?(d.textContent=``,e.forEach(([e,t],n)=>{n>0&&d.appendChild(document.createTextNode(`、 `));let r=typeof t==`string`?t:JSON.stringify(t),i=r.length>80?r.substring(0,80)+`...`:r,a=document.createElement(`span`);a.className=`confirm-arg`,a.style.marginRight=`8px`,r.length>80&&(a.title=r);let o=document.createElement(`strong`);o.textContent=`${e}:`,a.appendChild(o),a.appendChild(document.createTextNode(` ${i}`)),d.appendChild(a)}),d.style.display=`block`):d.style.display=`none`}let f=document.getElementById(`confirmMessage`);f&&(f.textContent=no(e)),eo();let p=Math.floor(o/1e3),m=document.getElementById(`confirmCountdownText`),h=document.getElementById(`confirmCountdown`);return m&&h&&(h.classList.remove(`warning`),h.style.display=`flex`,m.textContent=r(`dialog.remainingTime`,{time:$a(p)}),Za=setInterval(()=>{if(p--,p<=0){clearInterval(Za),Za=null,m.textContent=r(`dialog.remainingTime`,{time:`0:00`});return}m.textContent=r(`dialog.remainingTime`,{time:$a(p)}),p<=30&&h.classList.add(`warning`)},1e3)),s.style.display=`flex`,Qa=setTimeout(()=>{i.debug(`[SidePanel] confirm dialogtimeout,autodeny`),lo(!1,`single`)},o),!0}function io(){if(Xa)return!0;if(Ya.length===0)return!1;let e=Ya.shift();return ro(e)?(Xa=e,_a(Ja,e),!0):(e.resolve&&e.resolve(!1),!1)}function ao(){let e=document.getElementById(`confirmOverlay`);e&&(e.style.display=`none`);let t=document.getElementById(`confirmCountdown`);t&&(t.classList.remove(`warning`),t.style.display=`none`),C.currentConfirmToolCallId=null,C.currentConfirmSessionId=null}function oo(){if(Ya.length>0){da(Ja);return}ao(),fa(Ja)}function so(e){let t=Xa?.resolve;Xa=null,eo(),t&&t(e),oo()}function co(e){let t={...e,sessionId:e.sessionId||null};return i.debug(`[SidePanel] showconfirm dialog:`,t.toolName,e),Xa&&to(Xa,t)?(i.debug(`[SidePanel] duplicate confirm request, ignored:`,t.toolCallId),Promise.resolve(!1)):Ya.some(e=>to(e,t))?(i.debug(`[SidePanel] queued duplicate confirm, ignored:`,t.toolCallId),Promise.resolve(!1)):new Promise(e=>{Ya.push({...t,resolve:e}),da(Ja),Xa&&uo(),ha(Ja)})}function lo(e,t=`single`){if(!Xa)return;let n=Xa.toolCallId,r=Xa.sessionId;eo(),chrome.runtime.sendMessage({type:`TOOL_CONFIRMATION_RESPONSE`,toolCallId:n,confirmed:e,scope:t,sessionId:r}).catch(e=>{i.debug(`[SidePanel] send confirmationresponse failed:`,e.message)}),so(e)}function uo(){if(!Xa)return;let e=document.getElementById(`confirmMessage`);e&&(e.textContent=no(Xa))}function fo(e){let t=e?.toolCallId;if(!t)return;if(Xa&&Xa.toolCallId===t){i.debug(`[SidePanel] dismiss active confirm dialog (already settled by background):`,t),so(!1);return}let n=Ya.findIndex(e=>e.toolCallId===t);if(n>=0){i.debug(`[SidePanel] drop queued confirm dialog (already settled by background):`,t);let[e]=Ya.splice(n,1);e.resolve&&e.resolve(!1),uo(),ha(Ja)}}ua(Ja,{present:io,pendingCount:()=>Ya.length,refresh:()=>{Xa&&uo()}});function po(){let e=document.getElementById(`confirmApproveOnceBtn`),t=document.getElementById(`confirmApproveLoopBtn`),n=document.getElementById(`confirmDenyBtn`);e&&e.addEventListener(`click`,()=>lo(!0,`single`)),t&&t.addEventListener(`click`,()=>{lo(!0,Xa?.variant===`network`?`whitelist`:`loop`)}),n&&n.addEventListener(`click`,()=>lo(!1,`single`)),chrome.runtime.onMessage.addListener((e,t,n)=>e.type===`SHOW_CONFIRM_DIALOG`?(co(e.data),n({received:!0}),!1):e.type===`DISMISS_CONFIRM_DIALOG`?(fo(e.data),n({received:!0}),!1):!1)}var mo=t({closeCurrentSession:()=>ac,handleDuplicateSession:()=>Xs,handleSessionSwitch:()=>Ys,newSession:()=>xo,renderSessionTabs:()=>yo});n(`zh`,{session:{newSession:`新会话`,closeSession:`关闭会话`,taskCompleted:`任务已完成`,noMatch:`未找到匹配的会话`,rename:`重命名`,duplicate:`复制会话`,confirmCloseMessageWithTitle:`确定要关闭会话 "{title}" 吗?`,confirmCloseAllMessage:`确定要关闭所有 {count} 个会话吗?`,confirmCloseAllTitle:`关闭全部会话`,forkedFrom:`已从 "{title}" 分叉`,forkedSession:`已复制会话 "{title}"`,operationFailed:`操作失败:{message}`,sessionListTitle:`会话列表`,closeGroupAll:`全部关闭`,confirmCloseGroupMessage:`确定要关闭“{group}”下的 {count} 个会话吗?`,today:`今天`,yesterday:`昨天`,last7Days:`近 7 天`,earlier:`更早`,todayFormat:`{hour}:{minute}`,yesterdayFormat:`昨天 {hour}:{minute}`,daysAgo:`{count} 天前`,archive:`归档会话`,archiveEntry:`归档区`,archiveEntryTitle:`查看归档会话`,archivePanelTitle:`归档区`,archiveSearchPlaceholder:`搜索归档会话...`,archiveEmpty:`暂无归档会话`,archiveNoMatch:`未找到匹配的归档会话`,archiveHint:`归档只是移出视野,随时可以恢复`,archiveBusyRunning:`该会话任务还在执行,完成后再归档`,archiveBusyQueued:`该会话还有排队任务,先清空队列再归档`,archived:`已归档到归档区`,archivedRestored:`已恢复会话「{title}」`,archivedAt:`归档于 {time}`,restore:`恢复`,restoreTitle:`恢复到会话列表`,deleteForever:`彻底删除`,confirmDeleteForeverTitle:`彻底删除会话`,confirmDeleteForeverMessage:`「{title}」将被彻底删除,消息与执行记录都无法恢复。确定继续吗?`,archiveDeleted:`已彻底删除会话「{title}」`,backToSessionList:`返回会话列表`,expandSidebar:`展开会话列表`,collapseSidebar:`收起会话列表`,searchSessions:`搜索会话`,sortModeTitle:`会话排序`,sortManual:`手动排序(拖拽调整,与标签栏一致)`,sortRecent:`最近更新优先(按时间倒序,带时间分组)`}}),n(`en`,{session:{newSession:`New Session`,closeSession:`Close Session`,taskCompleted:`Task completed`,noMatch:`No matching sessions found`,rename:`Rename`,duplicate:`Duplicate`,confirmCloseMessageWithTitle:`Are you sure you want to close session "{title}"?`,confirmCloseAllMessage:`Are you sure you want to close all {count} sessions?`,confirmCloseAllTitle:`Close All Sessions`,forkedFrom:`Forked from "{title}"`,forkedSession:`Duplicated session "{title}"`,operationFailed:`Operation failed: {message}`,sessionListTitle:`Sessions`,closeGroupAll:`Close all`,confirmCloseGroupMessage:`Are you sure you want to close {count} sessions in "{group}"?`,today:`Today`,yesterday:`Yesterday`,last7Days:`Last 7 days`,earlier:`Earlier`,todayFormat:`{hour}:{minute}`,yesterdayFormat:`Yesterday {hour}:{minute}`,daysAgo:`{count}d ago`,archive:`Archive session`,archiveEntry:`Archived`,archiveEntryTitle:`View archived sessions`,archivePanelTitle:`Archived sessions`,archiveSearchPlaceholder:`Search archived sessions...`,archiveEmpty:`No archived sessions`,archiveNoMatch:`No archived sessions found`,archiveHint:`Archiving only hides a session — you can restore it anytime`,archiveBusyRunning:`This session is still running. Archive it when it finishes`,archiveBusyQueued:`This session still has queued tasks. Clear the queue first`,archived:`Moved to archive`,archivedRestored:`Session "{title}" restored`,archivedAt:`Archived {time}`,restore:`Restore`,restoreTitle:`Restore to session list`,deleteForever:`Delete permanently`,confirmDeleteForeverTitle:`Delete session permanently`,confirmDeleteForeverMessage:`"{title}" will be permanently deleted. Messages and execution logs cannot be recovered. Continue?`,archiveDeleted:`Session "{title}" permanently deleted`,backToSessionList:`Back to sessions`,expandSidebar:`Expand session list`,collapseSidebar:`Collapse session list`,searchSessions:`Search sessions`,sortModeTitle:`Session order`,sortManual:`Manual order (drag to arrange, same as tabs)`,sortRecent:`Most recent first (time order with day groups)`}});var B={visible:!1,highlightIndex:-1,filteredSessions:[]},ho={draggedId:null,sourceType:null};function go(e){if(!e)return``;let t=new Date(e),n=new Date,i=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),a=t.getTime();if(a>=i)return r(`session.todayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});if(a>=i-864e5)return r(`session.yesterdayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});let o=Math.floor((i-a)/864e5);return o<=7?r(`session.daysAgo`,{count:o}):t.getFullYear()===n.getFullYear()?`${t.getMonth()+1}/${t.getDate()}`:`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()}`}function _o(e){return e.sort((e,t)=>{let n=e.updatedAt?new Date(e.updatedAt).getTime():0;return(t.updatedAt?new Date(t.updatedAt).getTime():0)-n})}function vo(e){if(!e)return`earlier`;let t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),i=t.getTime();return i>=r?`today`:i>=r-864e5?`yesterday`:Math.floor((r-i)/864e5)<=7?`last7Days`:`earlier`}async function yo(e=null){let t=e||await ti({withActiveHistory:!1});C.sessions=t.list,C.activeSessionId=t.activeSessionId;let n=document.getElementById(`sessionTabs`),i=document.getElementById(`sessionTabsScroll`),a=document.getElementById(`sessionTabsActions`);!n||!i||!a||(i.style.opacity=``,i.innerHTML=``,t.list.forEach(e=>{let t=document.createElement(`div`);t.className=`session-tab`,t.dataset.sessionId=e.id,e.id===C.activeSessionId&&t.classList.add(`active`),t.title=e.title;let n=document.createElement(`span`);n.className=`session-tab-title`,n.textContent=e.title||r(`session.newSession`),t.appendChild(n);let a=document.createElement(`span`);if(a.className=`session-tab-close`,a.innerHTML=`✕`,a.title=r(`session.closeSession`),a.addEventListener(`click`,async t=>{if(t.stopPropagation(),(e.id===C.activeSessionId?C.messageHistory?.length||0:e.messageCount??e.messageHistory?.length??0)===0){Jo(await qo(e.id)),await ic();return}tc(e,async()=>{await ic()})}),t.appendChild(a),e.isGenerating||C.generatingSessionIds.has(e.id)){let e=document.createElement(`span`);e.className=`session-tab-indicator`,t.appendChild(e)}else if(C.completedSessionIds.has(e.id)&&e.id!==C.activeSessionId){let e=document.createElement(`span`);e.className=`session-tab-completed-indicator`,e.title=r(`session.taskCompleted`),t.appendChild(e)}let o=fr(e.id);if(o>0){let e=document.createElement(`span`);e.className=`session-tab-queue-badge`,e.textContent=String(o>99?`99+`:o),e.title=r(`queue.badgeTitle`,{count:o}),t.appendChild(e)}t.addEventListener(`click`,async n=>{if(n.preventDefault(),e.id!==C.activeSessionId&&!Gs){Gs=!0,i.querySelectorAll(`.session-tab.active`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`);try{await Ys(e.id)}finally{Gs=!1,C.activeSessionId!==e.id&&yo({list:C.sessions,activeSessionId:C.activeSessionId})}}}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),nc(t,e)}),t.addEventListener(`mousedown`,async t=>{t.button===1&&(t.preventDefault(),t.stopPropagation(),Jo(await qo(e.id)),await ic())}),t.draggable=!0,t.addEventListener(`dragstart`,t=>Ao(t,e.id)),t.addEventListener(`dragover`,e=>jo(e)),t.addEventListener(`dragleave`,e=>Mo(e)),t.addEventListener(`drop`,t=>No(t,e.id)),t.addEventListener(`dragend`,e=>Po(e)),i.appendChild(t)}),bo(),So(),Qo(),Ws(),$s(i),To(i),Eo(i),ko(i),Cs(),As())}function bo(){let e=document.getElementById(`sessionTabsMore`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,e=>{e.stopPropagation(),vs()})}async function xo(){let e=C.activeSessionId;await ni();let t=await ai();C.activeSessionId=t.id,C.messageHistory=[],C.activeCompaction=null,ri(t),document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:t.id,previousSessionId:e}})),yo()}function So(){let e=document.getElementById(`sessionTabsAdd`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,()=>xo())}var Co=0,wo=0;function To(e){let t=document.getElementById(`sessionTabsMore`);if(!t)return;if(!fs()){t.style.display=`none`;return}let n=e.scrollWidth>e.clientWidth;t.style.display=n||Co>0?`flex`:`none`}async function Eo(e){let t=++wo,n;try{n=await di()}catch{return}t===wo&&(Co=n.length,To(e))}var Do=null;function Oo(){if(Do)return;let e=document.getElementById(`sessionTabsScroll`);e&&(Do=new ResizeObserver(()=>{requestAnimationFrame(()=>{To(e)})}),Do.observe(e))}function ko(e){let t=e.querySelector(`.session-tab.active`);if(t){let n=t.offsetLeft,r=t.offsetWidth;e.scrollLeft=n-(e.clientWidth-r)/2}e.style.opacity=`1`}function Ao(e,t){ho.draggedId=t,ho.sourceType=`tab`,e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),e.currentTarget.classList.add(`dragging`)}function jo(e){e.preventDefault(),e.dataTransfer.dropEffect=`move`,e.currentTarget.classList.add(`drag-over`)}function Mo(e){e.currentTarget.classList.remove(`drag-over`)}async function No(e,t){e.preventDefault(),e.currentTarget.classList.remove(`drag-over`);let n=ho.draggedId;if(!n||n===t)return;let r=C.sessions||[],i=r.findIndex(e=>e.id===n),a=r.findIndex(e=>e.id===t);if(i===-1||a===-1)return;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s),C.sessions=o,await li(o.map(e=>e.id)),yo()}function Po(e){e.currentTarget.classList.remove(`dragging`),document.querySelectorAll(`.session-tab.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),ho.draggedId=null,ho.sourceType=null}function Fo(){B.visible?Lo():Io()}async function Io(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);if(!e||!t)return;let n=await ti();C.sessions=n.list,C.activeSessionId=n.activeSessionId,B.filteredSessions=_o([...n.list]),B.highlightIndex=-1,B.visible=!0,Is(),zo(),t.classList.add(`show`);let r=document.getElementById(`sessionDropdownCloseBtn`);r&&(r.onclick=()=>Lo());let i=document.getElementById(`sessionDropdownSearch`),a=document.getElementById(`sessionDropdownSearchClear`);i&&(i.value=B.lastSearchText||``,Ro(),B.lastSearchText&&Go(B.lastSearchText),setTimeout(()=>i.focus(),50),i.oninput=()=>{B.lastSearchText=i.value,Ro(),Go(i.value)},i.onkeydown=e=>{$o(e)}),a&&(a.onclick=()=>{i&&(i.value=``,B.lastSearchText=``,Ro(),Go(``),i.focus())}),e.classList.add(`active`)}function Lo(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);t&&t.classList.remove(`show`),e&&e.classList.remove(`active`);let n=document.getElementById(`sessionDropdownSearch`);n&&(B.lastSearchText=n.value,n.oninput=null,n.onkeydown=null);let r=document.getElementById(`sessionDropdownSearchClear`);r&&(r.onclick=null),B.visible=!1,B.highlightIndex=-1,B.filteredSessions=[]}function Ro(){let e=document.getElementById(`sessionDropdownSearch`),t=document.getElementById(`sessionDropdownSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function zo(){Bo({listEl:document.getElementById(`sessionDropdownList`),filteredSessions:B.filteredSessions,highlightIndex:B.highlightIndex,onSelect:e=>Ko(e)})}function Bo({listEl:e,filteredSessions:t,highlightIndex:n,onSelect:i,grouped:a=!0,draggable:o=!1}){if(!e)return;if(e.innerHTML=``,t.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(`session.noMatch`),e.appendChild(t);return}let s={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},c={};a&&t.forEach(e=>{let t=vo(e.updatedAt);c[t]=(c[t]||0)+1});let l=null;t.forEach((t,u)=>{if(a){let n=vo(t.updatedAt);if(n!==l){l=n;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let i=document.createElement(`span`);if(i.textContent=s[n]||n,t.appendChild(i),(c[n]||0)>0){let e=document.createElement(`button`);e.className=`session-dropdown-group-close`,e.textContent=r(`session.closeGroupAll`),e.onclick=e=>{e.stopPropagation(),Zo(n,s[n]||n)},t.appendChild(e)}e.appendChild(t)}}let d=Wo(t,{index:u,highlightIndex:n,onSelect:i});o&&Ho(d,t.id),e.appendChild(d)})}var Vo=null;function Ho(e,t){e.draggable=!0,e.classList.add(`draggable`),e.addEventListener(`dragstart`,n=>{Vo=t,n.dataTransfer.effectAllowed=`move`,n.dataTransfer.setData(`text/plain`,t),e.classList.add(`dragging`)}),e.addEventListener(`dragover`,n=>{!Vo||Vo===t||(n.preventDefault(),n.dataTransfer.dropEffect=`move`,e.classList.add(`drag-over`))}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drag-over`)),e.addEventListener(`drop`,n=>{n.preventDefault(),n.stopPropagation(),e.classList.remove(`drag-over`),Uo(Vo,t)}),e.addEventListener(`dragend`,()=>{e.classList.remove(`dragging`),document.querySelectorAll(`.session-dropdown-item.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),Vo=null})}async function Uo(e,t){let n=e;if(Vo=null,!n||n===t)return;let r=C.sessions||[],i=r.findIndex(e=>e.id===n),a=r.findIndex(e=>e.id===t);if(i===-1||a===-1)return;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s),C.sessions=o,await li(o.map(e=>e.id)),await yo()}function Wo(e,{index:t,highlightIndex:n,onSelect:i}){let a=document.createElement(`div`);a.className=`session-dropdown-item`,a.dataset.sessionId=e.id,a.dataset.index=t,e.id===C.activeSessionId&&a.classList.add(`active`),t===n&&a.classList.add(`highlighted`);let o=e.isGenerating||C.generatingSessionIds.has(e.id);if(C.completedSessionIds.has(e.id)&&e.id!==C.activeSessionId&&!o){let e=document.createElement(`span`);e.className=`session-dropdown-item-completed`,e.title=r(`session.taskCompleted`),a.appendChild(e)}let s=fr(e.id);if(s>0){let e=document.createElement(`span`);e.className=`session-dropdown-item-queue`,e.textContent=String(s>99?`99+`:s),e.title=r(`queue.badgeTitle`,{count:s}),a.appendChild(e)}let c=document.createElement(`span`);if(c.className=`session-dropdown-item-icon`,o){let e=document.createElement(`span`);e.className=`session-dropdown-item-running`,c.appendChild(e)}else c.innerHTML=`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`;a.appendChild(c);let l=document.createElement(`span`);if(l.className=`session-dropdown-item-title`,l.textContent=e.title||r(`session.newSession`),l.title=e.title||r(`session.newSession`),a.appendChild(l),e.id===C.activeSessionId){let e=document.createElement(`span`);e.className=`session-dropdown-item-check`,e.innerHTML=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`,a.appendChild(e)}let u=document.createElement(`span`);u.className=`session-dropdown-item-time`,u.textContent=go(e.updatedAt),a.appendChild(u);let d=document.createElement(`span`);d.className=`session-dropdown-item-actions`;let f=document.createElement(`span`);f.className=`session-dropdown-item-rename`,f.title=r(`session.rename`),f.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,f.addEventListener(`click`,t=>{t.stopPropagation(),t.preventDefault(),ec(e)}),d.appendChild(f);let p=document.createElement(`span`);p.className=`session-dropdown-item-duplicate`,p.title=r(`session.duplicate`),p.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,p.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await Xs(e.id);let n=await ti({withActiveHistory:!1});C.sessions=n.list,C.activeSessionId=n.activeSessionId,Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}),d.appendChild(p);let m=document.createElement(`span`);m.className=`session-dropdown-item-archive`,m.title=r(`session.archive`),m.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,m.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await Ps(e.id),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}),d.appendChild(m);let h=document.createElement(`span`);return h.className=`session-dropdown-item-close`,h.innerHTML=`✕`,h.title=r(`session.closeSession`),h.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await Yo(e.id)}),d.appendChild(h),a.appendChild(d),a.addEventListener(`click`,async t=>{t.preventDefault(),await i(e.id)}),a}function Go(e){let t=C.sessions||[],n;if(!e.trim())n=[...t];else{let i=e.trim().toLowerCase();n=t.filter(e=>(e.title||r(`session.newSession`)).toLowerCase().includes(i))}B.filteredSessions=_o(n),B.highlightIndex=-1,zo()}async function Ko(e){Lo(),e!==C.activeSessionId&&await Ys(e)}async function qo(e){let t=fr(e)+ur(e).length;return await si(e),t}function Jo(e){e<=0||F(r(`queue.sessionDropped`,{count:e}),`info`,3e3)}async function Yo(e){let t=(C.sessions||[]).find(t=>t.id===e);t&&((e===C.activeSessionId?C.messageHistory?.length||0:t.messageCount??t.messageHistory?.length??0)>0&&!await js(r(`session.confirmCloseMessageWithTitle`,{title:t.title}),r(`session.closeSession`))||(Jo(await qo(e)),await ic(),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)))}async function Xo(){let e=C.sessions||[];if(e.length===0||!await js(r(`session.confirmCloseAllMessage`,{count:e.length}),r(`session.confirmCloseAllTitle`)))return;let t=0;for(let n of e)t+=await qo(n.id);Jo(t),await ic(),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}async function Zo(e,t){let n=(C.sessions||[]).filter(t=>vo(t.updatedAt)===e);if(n.length===0||!await js(r(`session.confirmCloseGroupMessage`,{group:t,count:n.length}),r(`session.closeSession`)))return;let i=0;for(let e of n)i+=await qo(e.id);Jo(i),await ic(),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}function Qo(){let e=document.getElementById(`sessionDropdownCloseAll`),t=document.getElementById(`sessionDropdown`);if(t){if(e){let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,async e=>{e.stopPropagation(),await Xo()})}t.addEventListener(`click`,e=>{e.stopPropagation()})}}function $o(e){if(!B.visible)return;let t=B.filteredSessions.length;if(t===0){e.key===`Escape`&&Lo();return}switch(e.key){case`ArrowDown`:e.preventDefault(),B.highlightIndex=Math.min(B.highlightIndex+1,t-1),zo(),es(document.getElementById(`sessionDropdownList`));break;case`ArrowUp`:e.preventDefault(),B.highlightIndex=Math.max(B.highlightIndex-1,0),zo(),es(document.getElementById(`sessionDropdownList`));break;case`Enter`:if(e.preventDefault(),B.highlightIndex>=0&&B.highlightIndex<t){let e=B.filteredSessions[B.highlightIndex];Ko(e.id)}break;case`Escape`:e.preventDefault(),Lo();break}}function es(e){let t=(e||document).querySelector(`.session-dropdown-item.highlighted`);t&&t.scrollIntoView({block:`nearest`})}var ts=560,ns=200,rs=480,is=360,as=240,os=`sessionSidebarExpanded`,ss=`sessionSidebarWidth`,cs=`sessionSidebarSortMode`,ls=`manual`,us=`recent`,V={expanded:!1,width:as,sortMode:ls,narrow:!1,pendingRestore:!1,highlightIndex:-1,filteredSessions:[],inited:!1,lastActiveId:null};function ds(e){let t=document.getElementById(`mainRow`),n=t?Math.max(ns,t.clientWidth-is):rs;return Math.max(ns,Math.min(e,rs,n))}function fs(){let e=document.getElementById(`mainRow`);return e?e.clientWidth<ts:!0}function ps(){let e=document.getElementById(`sessionSidebar`);if(!e)return;V.narrow=fs(),e.classList.toggle(`sidebar-hidden`,V.narrow),e.classList.toggle(`expanded`,!V.narrow&&V.expanded),e.style.setProperty(`--session-sidebar-width`,`${V.width}px`),ms();let t=document.getElementById(`sessionSidebarToggle`);t&&t.classList.toggle(`sidebar-hidden`,V.narrow||V.expanded);let n=document.getElementById(`sessionTabs`);if(n){let e=!V.narrow&&V.expanded;if(n.classList.toggle(`tabs-hidden`,e),!e){let e=document.getElementById(`sessionTabsScroll`);e&&ko(e)}}}function ms(){let e=!V.narrow&&V.expanded?V.width:0;document.body.style.setProperty(`--session-sidebar-offset`,`${e}px`)}async function hs(){try{await chrome.storage.local.set({[os]:V.expanded,[ss]:V.width,[cs]:V.sortMode})}catch{}}function gs(){fs()||(V.expanded=!0,ps(),hs(),Cs())}function _s(){V.expanded=!1,ps(),hs()}function vs(){if(fs()){Fo();return}V.expanded?_s():gs()}function ys(){let e=document.getElementById(`sessionSidebarList`),t=V.sortMode===us,n=!!(document.getElementById(`sessionSidebarSearch`)?.value||``).trim();Bo({listEl:e,filteredSessions:V.filteredSessions,highlightIndex:V.highlightIndex,onSelect:e=>ws(e),grouped:t,draggable:!t&&!n});let r=C.activeSessionId;r&&V.lastActiveId!==r&&(V.lastActiveId=r,e?.querySelector(`.session-dropdown-item.active`)?.scrollIntoView({block:`nearest`}))}function bs(e){let t=C.sessions||[],n;if(!e.trim())n=[...t];else{let i=e.trim().toLowerCase();n=t.filter(e=>(e.title||r(`session.newSession`)).toLowerCase().includes(i))}V.filteredSessions=V.sortMode===us?_o(n):n.reverse(),V.highlightIndex=-1,ys()}function xs(){document.querySelectorAll(`.session-sidebar-sort-btn`).forEach(e=>{let t=e.dataset.mode===V.sortMode;e.classList.toggle(`active`,t),e.setAttribute(`aria-pressed`,t?`true`:`false`)})}function Ss(e){e!==ls&&e!==us||V.sortMode!==e&&(V.sortMode=e,xs(),V.lastActiveId=null,bs(document.getElementById(`sessionSidebarSearch`)?.value||``),hs())}function Cs(){let e=document.getElementById(`sessionSidebar`);!e||!e.classList.contains(`expanded`)||bs(document.getElementById(`sessionSidebarSearch`)?.value||``)}async function ws(e){e!==C.activeSessionId&&await Ys(e)}function Ts(e){let t=V.filteredSessions,n=t.length;if(n===0){e.key===`Escape`&&_s();return}switch(e.key){case`ArrowDown`:e.preventDefault(),V.highlightIndex=Math.min(V.highlightIndex+1,n-1),ys(),es(document.getElementById(`sessionSidebarList`));break;case`ArrowUp`:e.preventDefault(),V.highlightIndex=Math.max(V.highlightIndex-1,0),ys(),es(document.getElementById(`sessionSidebarList`));break;case`Enter`:e.preventDefault(),V.highlightIndex>=0&&V.highlightIndex<n&&ws(t[V.highlightIndex].id);break;case`Escape`:e.preventDefault(),_s();break}}function Es(){let e=document.getElementById(`sessionSidebarSearch`),t=document.getElementById(`sessionSidebarSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function Ds(){let e=document.getElementById(`sessionSidebar`),t=document.getElementById(`sessionSidebarGrip`);!e||!t||t.addEventListener(`mousedown`,t=>{t.preventDefault();let n=t.clientX,r=V.width;e.classList.add(`resizing`);function i(t){let i=ds(r+(t.clientX-n));V.width=i,e.style.setProperty(`--session-sidebar-width`,`${i}px`),ms()}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),hs()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function Os(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{requestAnimationFrame(()=>{let e=fs();e!==V.narrow&&(e&&V.expanded?V.pendingRestore=!0:!e&&V.pendingRestore&&(V.pendingRestore=!1),ps(),!e&&V.expanded&&Cs())})}).observe(e)}function ks(){fs()?Io():gs()}async function As(){if(V.inited||!document.getElementById(`sessionSidebar`))return;V.inited=!0;try{let e=await chrome.storage.local.get([os,ss,cs]);V.expanded=e[os]===!0,typeof e[ss]==`number`&&(V.width=ds(e[ss])),(e[cs]===us||e[cs]===ls)&&(V.sortMode=e[cs])}catch{}xs(),fs()&&V.expanded&&(V.pendingRestore=!0),ps(),Cs(),document.getElementById(`sessionSidebarToggle`)?.addEventListener(`click`,()=>vs()),document.getElementById(`sessionSidebarAdd`)?.addEventListener(`click`,()=>{xo()}),document.getElementById(`sessionSidebarCollapse`)?.addEventListener(`click`,()=>_s()),document.querySelectorAll(`.session-sidebar-sort-btn`).forEach(e=>{e.addEventListener(`click`,()=>Ss(e.dataset.mode))}),document.getElementById(`sessionSidebarArchiveEntry`)?.addEventListener(`click`,()=>{Ls()}),document.getElementById(`sessionSidebarCloseAll`)?.addEventListener(`click`,async e=>{e.stopPropagation(),await Xo()});let e=document.getElementById(`sessionSidebarSearch`),t=document.getElementById(`sessionSidebarSearchClear`);e&&(e.addEventListener(`input`,()=>{Es(),bs(e.value)}),e.addEventListener(`keydown`,e=>{Ts(e)})),t&&t.addEventListener(`click`,()=>{e&&(e.value=``,Es(),bs(``),e.focus())}),Ds(),Os(),Is()}function js(e,t){return new Promise(t=>{let n=document.getElementById(`sessionDeleteModal`),r=document.getElementById(`sessionDeleteMessage`),i=document.getElementById(`sessionDeleteConfirmBtn`),a=document.getElementById(`sessionDeleteCancelBtn`),o=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!r){t(!1);return}r.textContent=e;let s=()=>{n.classList.remove(`show`),i.removeEventListener(`click`,c),a.removeEventListener(`click`,l),o.removeEventListener(`click`,l)},c=()=>{s(),t(!0)},l=()=>{s(),t(!1)};i.addEventListener(`click`,c),a.addEventListener(`click`,l),o.addEventListener(`click`,l),n.classList.add(`show`)})}var Ms=``,Ns=!1;async function Ps(e){if(!e)return;let t=fi(e);if(!t.ok){t.reason===`running`?F(r(`session.archiveBusyRunning`),`warning`):t.reason===`queued`&&F(r(`session.archiveBusyQueued`),`warning`);return}let n=e===C.activeSessionId,i=await pi(e);if(!i?.ok){i?.reason===`running`?F(r(`session.archiveBusyRunning`),`warning`):i?.reason===`queued`?F(r(`session.archiveBusyQueued`),`warning`):F(r(`session.operationFailed`,{message:i?.reason||`unknown`}),`error`);return}if(document.dispatchEvent(new CustomEvent(`session-archived`,{detail:{sessionId:e}})),n)await Fs(e);else{let e=await ti();C.sessions=e.list,yo(e)}await Is(),F(r(`session.archived`),`info`)}async function Fs(e){let t=_o([...(await ti()).list]).filter(t=>t.id!==e);if(t.length>0){await Ys(t[0].id);return}await ai(),await ic()}async function Is(){let e=[`sessionArchiveEntryLabel`,`sessionSidebarArchiveLabel`].map(e=>document.getElementById(e));if(!e.some(Boolean))return;Co=(await di()).length;let t=document.getElementById(`sessionTabsScroll`);t&&To(t);let n=r(`session.archiveEntry`);e.forEach(e=>{e&&(e.textContent=n)})}async function Ls(){let e=document.getElementById(`sessionArchivePanel`);if(!e)return;Ws(),Ms=``;let t=document.getElementById(`sessionArchiveSearch`);t&&(t.value=``),zs(),await Bs(),e.classList.add(`show`),Lo()}function Rs(){let e=document.getElementById(`sessionArchivePanel`);e&&e.classList.remove(`show`)}function zs(){let e=document.getElementById(`sessionArchiveSearchClear`);e&&(e.style.display=Ms?`flex`:`none`)}async function Bs(){let e=document.getElementById(`sessionArchiveList`);if(!e)return;let t=await di(),n=Ms.trim().toLowerCase(),i=n?t.filter(e=>(e.title||``).toLowerCase().includes(n)):t;if(e.innerHTML=``,i.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(n?`session.archiveNoMatch`:`session.archiveEmpty`),e.appendChild(t);return}let a={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},o=null;i.forEach(t=>{let n=vo(t.archivedAt);if(n!==o){o=n;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let r=document.createElement(`span`);r.textContent=a[n]||n,t.appendChild(r),e.appendChild(t)}e.appendChild(Vs(t))})}function Vs(e){let t=document.createElement(`div`);t.className=`session-dropdown-item session-archive-item`,t.dataset.sessionId=e.id,t.title=e.title||r(`session.newSession`);let n=document.createElement(`span`);n.className=`session-dropdown-item-icon`,n.innerHTML=`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,t.appendChild(n);let i=document.createElement(`span`);i.className=`session-dropdown-item-title`,i.textContent=e.title||r(`session.newSession`),t.appendChild(i);let a=document.createElement(`span`);a.className=`session-dropdown-item-time`,a.textContent=r(`session.archivedAt`,{time:go(e.archivedAt)}),t.appendChild(a);let o=document.createElement(`span`);o.className=`session-dropdown-item-actions`;let s=document.createElement(`span`);s.className=`session-dropdown-item-restore`,s.title=r(`session.restoreTitle`),s.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 14 4 9 9 4"/><path d="M20 20v-7a4 4 0 0 0-4-4H4"/></svg>`,s.addEventListener(`click`,async t=>{t.stopPropagation(),await Hs(e.id)}),o.appendChild(s);let c=document.createElement(`span`);return c.className=`session-dropdown-item-delete`,c.title=r(`session.deleteForever`),c.innerHTML=`✕`,c.addEventListener(`click`,async t=>{t.stopPropagation(),await Us(e)}),o.appendChild(c),t.appendChild(o),t.addEventListener(`click`,async()=>{await Hs(e.id,{enter:!0})}),t}async function Hs(e,{enter:t=!1}={}){if(!await mi(e)){F(r(`session.operationFailed`,{message:`not found`}),`error`),await Bs();return}let n=await ti();C.sessions=n.list;let i=n.list.find(t=>t.id===e)?.title||r(`session.newSession`);Rs(),await Bs(),await Is(),t?await Ys(e):yo(n),F(r(`session.archivedRestored`,{title:i}),`success`)}async function Us(e){let t=e.title||r(`session.newSession`);await js(r(`session.confirmDeleteForeverMessage`,{title:t}),r(`session.confirmDeleteForeverTitle`))&&(await hi(e.id),await Bs(),await Is(),document.dispatchEvent(new CustomEvent(`session-deleted`,{detail:{sessionId:e.id}})),F(r(`session.archiveDeleted`,{title:t}),`success`))}function Ws(){if(Ns)return;let e=document.getElementById(`sessionArchivePanel`),t=document.getElementById(`sessionArchiveEntry`);if(!e||!t)return;Ns=!0,t.addEventListener(`click`,()=>{Ls()});let n=document.getElementById(`sessionArchiveBackBtn`);n&&n.addEventListener(`click`,()=>{Rs(),ks()});let r=document.getElementById(`sessionArchiveCloseBtn`);r&&r.addEventListener(`click`,()=>Rs());let i=document.getElementById(`sessionArchiveSearch`),a=document.getElementById(`sessionArchiveSearchClear`);i&&(i.addEventListener(`input`,()=>{Ms=i.value,zs(),Bs()}),i.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),Rs(),ks())})),a&&a.addEventListener(`click`,()=>{i&&(i.value=``,Ms=``,zs(),Bs(),i.focus())}),document.addEventListener(`session-archived`,()=>{e.classList.contains(`show`)&&Bs()}),document.addEventListener(`session-deleted`,()=>{e.classList.contains(`show`)&&Bs()})}var Gs=!1,Ks=500;function qs(e){let t=`scrollPosition_${e||`default`}`;chrome.storage.local.get([t],e=>{let n=document.getElementById(`chatContainer`);n&&e[t]!==void 0&&(n.scrollTop=e[t]),A(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>SS);return{updateScrollButtonState:e}},void 0).then(({updateScrollButtonState:e})=>e()).catch(()=>{})})}function Js(e,t){setTimeout(()=>{C.activeSessionId===e&&(Fe(t)||qs(e))},Ks)}async function Ys(e,{focusMessageId:t=null}={}){let n=C.activeSessionId;if(!await oi(e))return;let r=`agentEnabledTools_${C.activeAgentId||`default`}`,i=`agentMcpClosedServers_${C.activeAgentId||`default`}`,[a,o,s,c]=await Promise.all([ti(),chrome.storage.local.get([i,`ragTools`,`ragToolsIntroduced`]),chrome.storage.local.get([r,`enabledTools`]),C.activeAgentId?ft(C.activeAgentId):Promise.resolve(null)]);C.sessions=a.list,C.activeSessionId=e;let l=o.ragTools||[];C.mcpClosedServers=o[i]||[];let u=!!s[r],d=s[r]||s.enabledTools;if(u||d&&d.length>0){let e=ta(l),t=d.filter(t=>e.has(t));if(u)C.enabledTools=t;else{let e=f.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);C.enabledTools=[...t,...e]}let n=ea(C.enabledTools,l,o.ragToolsIntroduced);C.enabledTools=n.tools,C.enabledTools.length!==d.length&&chrome.storage.local.set({[r]:C.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{C.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let e=ea(C.enabledTools,l,o.ragToolsIntroduced);C.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[r]:C.enabledTools})}C.activeAgentToolIds=c?c.toolIds:null,C.activeAgentMcpExcludedServerIds=c?c.mcpExcludedServerIds??null:null,document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,...t?{skipScrollRestore:!0}:{}}})),ei(e),yo(a),Zs(),XT();try{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await A(async()=>{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await Promise.resolve().then(()=>zm);return{refreshBookmarkPanel:e,updateBookmarkButtons:t}},void 0);e(),setTimeout(()=>t(),100)}catch{}let p=document.getElementById(`toolsPopupOverlay`);p&&p.classList.contains(`show`)&&(Bi(),Ji(),Yi()),Qi(),t&&Js(e,t)}async function Xs(e,t=null){if(e)try{let n=await vi(e,t);await Ys(n.id),F(r(t?`session.forkedFrom`:`session.forkedSession`,{title:n.title}),`success`)}catch(e){i.error(`[SessionUI] copy/forksession failed:`,e),F(r(`session.operationFailed`,{message:e.message}),`error`)}}function Zs(){let e=document.querySelector(`.model-display`);e&&C.currentModel&&(e.textContent=C.currentModel);let t=document.getElementById(`enableToolsBtn`);t&&(t.checked=C.useTools);let n=document.getElementById(`tempIconValue`);n&&C.temperature!==void 0&&(n.textContent=C.temperature.toFixed(2))}var Qs=new WeakSet;function $s(e){Qs.has(e)||(Qs.add(e),e.addEventListener(`wheel`,t=>{e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY)},{passive:!1}))}function ec(e){let t=document.getElementById(`sessionRenameModal`),n=document.getElementById(`sessionRenameInput`),r=document.getElementById(`sessionRenameConfirmBtn`),i=document.getElementById(`sessionRenameCancelBtn`),a=document.getElementById(`sessionRenameCloseBtn`);if(!t||!n)return;n.value=e.title;let o=()=>{t.classList.remove(`show`),r.removeEventListener(`click`,s),i.removeEventListener(`click`,c),a.removeEventListener(`click`,c)},s=async()=>{let t=n.value.trim();if(t&&t!==e.title){await ci(e.id,t),yo();let n=await ti();C.sessions=n.list,C.activeSessionId=n.activeSessionId,Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}o()},c=()=>{o()};r.addEventListener(`click`,s),i.addEventListener(`click`,c),a.addEventListener(`click`,c),n.onkeydown=e=>{e.key===`Enter`?s():e.key===`Escape`&&c()},t.classList.add(`show`),setTimeout(()=>{n.focus(),n.select()},50)}function tc(e,t){let n=document.getElementById(`sessionDeleteModal`),i=document.getElementById(`sessionDeleteMessage`),a=document.getElementById(`sessionDeleteConfirmBtn`),o=document.getElementById(`sessionDeleteCancelBtn`),s=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!i)return;i.textContent=r(`session.confirmCloseMessageWithTitle`,{title:e.title});let c=()=>{n.classList.remove(`show`),a.removeEventListener(`click`,l),o.removeEventListener(`click`,u),s.removeEventListener(`click`,u)},l=async()=>{Jo(await qo(e.id)),t&&await t(),c()},u=()=>{c()};a.addEventListener(`click`,l),o.addEventListener(`click`,u),s.addEventListener(`click`,u),n.classList.add(`show`),requestAnimationFrame(()=>a.focus())}function nc(e,t){let n=document.querySelector(`.session-context-menu`);n&&n.remove();let i=document.createElement(`div`);i.className=`session-context-menu`,i.style.left=e.clientX+`px`,i.style.top=e.clientY+`px`;let a=rc(r(`session.rename`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,()=>{i.remove(),ec(t)});i.appendChild(a);let o=rc(r(`session.duplicate`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,()=>{i.remove(),Xs(t.id)});i.appendChild(o);let s=rc(r(`session.archive`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,async()=>{i.remove(),await Ps(t.id)});i.appendChild(s);let c=rc(r(`session.closeSession`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,async()=>{if(i.remove(),(t.id===C.activeSessionId?C.messageHistory?.length||0:t.messageCount??t.messageHistory?.length??0)===0){Jo(await qo(t.id)),await ic();return}tc(t,async()=>{await ic()})},`danger`);i.appendChild(c),document.body.appendChild(i);let l=e=>{i.contains(e.target)||(i.remove(),document.removeEventListener(`click`,l))};setTimeout(()=>document.addEventListener(`click`,l),0)}function rc(e,t=``,n,r=``){let i=document.createElement(`div`);return i.className=`session-context-menu-item `+r,t?i.innerHTML=`${t}<span>${e}</span>`:i.textContent=e,i.addEventListener(`click`,n),i}async function ic(){let e=C.activeSessionId,t=await ti();t.activeSessionId||(await ai(),t=await ti()),C.activeSessionId=t.activeSessionId,C.sessions=t.list;let n=t.list.find(e=>e.id===t.activeSessionId);if(C.messageHistory=n&&n.messageHistory||[],C.activeCompaction=n?.contextCompaction||null,ri(n),C.activeAgentId=n&&n.agentId||null,C.activeAgentId){let e=await ft(C.activeAgentId);C.activeAgentToolIds=e?e.toolIds:null,C.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null}else C.activeAgentToolIds=null,C.activeAgentMcpExcludedServerIds=null;document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:C.activeSessionId,previousSessionId:e}})),yo(),await XT()}async function ac(){let e=C.activeSessionId;if(!e)return;let t=C.sessions?.find(t=>t.id===e);if(t){if((C.messageHistory?.length||0)===0){Jo(await qo(e)),await ic();return}tc(t,async()=>{await ic()})}}document.addEventListener(`generating-state-changed`,()=>{yo()}),document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{Oo(),As()}):(Oo(),As()),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`].join(``),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M12.146.146a.5.5 0 0 1 .708 0l2.5 2.5a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12h.5a.5.5 0 0 1 .5.5v.5a.5.5 0 0 1-.5.5h-.5a.5.5 0 0 1-.468-.325z"/>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="12" cy="12" r="10"></circle>`,`<polyline points="12 6 12 12 16 14"></polyline>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<line x1="18" y1="6" x2="6" y2="18"></line>`,`<line x1="6" y1="6" x2="18" y2="18"></line>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="7 13 12 18 17 13"></polyline>`,`<polyline points="7 6 12 11 17 6"></polyline>`,`</svg>`].join(``);var oc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`,sc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`,cc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>`,lc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,uc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,dc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>`;[`<svg class="tool-call-icon exec" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>`,`<polyline points="14 2 14 8 20 8"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>`,`</svg>`].join(``),n(`zh`,{uiProto:{defaultTitle:`原型`,optimizePrompt:`请帮我优化这个UI原型界面 {id}({title}),`,loadFailed:`加载失败`,noDescription:`暂无描述`,previewInPanel:`面板内预览`,continueOptimizeTitle:`继续优化`,downloadPrototype:`下载原型`,confirmDeleteTitle:`确认删除`,confirmDeleteMessage:`确定删除原型 "{title}" 吗?此操作不可撤销。`,deleteFailed:`删除失败: {message}`,justNow:`刚刚`,minutesAgo:`{count} 分钟前`,hoursAgo:`{count} 小时前`}}),n(`en`,{uiProto:{defaultTitle:`Prototype`,optimizePrompt:`Please help me optimize this UI prototype {id} ({title}), `,loadFailed:`Load failed`,noDescription:`No description`,previewInPanel:`Preview in panel`,continueOptimizeTitle:`Continue optimizing`,downloadPrototype:`Download prototype`,confirmDeleteTitle:`Confirm delete`,confirmDeleteMessage:`Are you sure you want to delete prototype "{title}"? This action cannot be undone.`,deleteFailed:`Delete failed: {message}`,justNow:`Just now`,minutesAgo:`{count} minutes ago`,hoursAgo:`{count} hours ago`}});var fc=null,pc=1,mc=.25,hc=2,gc=.1;function _c(e){let t=e.trim();return/^\s*<!DOCTYPE\s/i.test(t)||/^\s*<html[\s>]/i.test(t)?/<\/head>/i.test(t)?t.replace(/<\/head>/i,`<style>html,body{overflow:auto!important;height:auto!important;}</style></head>`):/<body[\s>]/i.test(t)?t.replace(/<body([\s>])/i,`<body$1<style>html,body{overflow:auto!important;height:auto!important;}</style>`):t:`<!DOCTYPE html>
|
|
60
|
+
`,e.addEventListener(`click`,()=>Va(-1)),g.appendChild(e);let t=document.getElementById(`clarifyCustomInput`);t&&g.appendChild(t)}let _=document.getElementById(`clarifyCustomInput`);_&&_.classList.remove(`show`);let v=document.getElementById(`clarifyAdditionalInfo`);v&&v.classList.toggle(`show`,o);let y=document.getElementById(`clarifyCustomTextarea`);y&&(y.value=``);let b=document.getElementById(`clarifyAdditionalTextarea`);b&&(b.value=``),l.classList.add(`show`);let x=document.querySelector(`#clarifyContainer .clarify-content`),S=document.querySelector(`#clarifyContainer .clarify-header`);return x&&(x.scrollTop=0),S&&S.classList.remove(`scrolled`),ba=null,xa=!1,Da(),Ta(s),i.debug(`[SidePanel] clarification dialogshown:`,e.toolCallId,t),!0}function Na(){if(z)return!0;if(ya.length===0)return!1;let e=ya.shift();return Ma(e)?(z=e,_a(va,e),!0):(i.error(`[SidePanel] clarify overlay missing, settle as unanswered:`,e.toolCallId),Pa(e),P(r(`clarify.dropped`),`warning`),!1)}function Pa(e){Promise.resolve(chrome.runtime.sendMessage({type:`CLARIFY_RESPONSE`,toolCallId:e.toolCallId,selectedOption:-1,customInput:``,additionalInfo:``})).catch(e=>{i.debug(`[SidePanel] send unanswered clarify response failed:`,e?.message)})}function Fa(){if(ya.length>0){da(va);return}Ia(),fa(va)}function Ia(){let e=document.getElementById(`clarifyOverlay`);e&&e.classList.remove(`show`),C.currentClarifyToolCallId=null,C.currentClarifySessionId=null,Ea()}function La(){z=null,Fa()}function Ra(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&e.question===t.question}function za(e){let t={...e,sessionId:e.sessionId||null};if(i.debug(`[SidePanel] showclarification dialog:`,t.toolCallId,e),z&&Ra(z,t)){i.debug(`[SidePanel] duplicate clarify request, ignored:`,t.toolCallId);return}if(ya.some(e=>Ra(e,t))){i.debug(`[SidePanel] queued duplicate clarify, ignored:`,t.toolCallId);return}ya.push(t),da(va),ja(),ha(va)}function Ba(){if(z){La();return}Ia()}function Va(e){document.querySelectorAll(`.clarify-option-item`).forEach(e=>{e.classList.remove(`selected`),e.setAttribute(`aria-checked`,`false`),e.setAttribute(`tabindex`,`-1`)});let t=document.querySelector(`.clarify-option-item[data-index="${e}"]`);t&&(t.classList.add(`selected`),t.setAttribute(`aria-checked`,`true`),t.setAttribute(`tabindex`,`0`));let n=document.getElementById(`clarifyCustomInput`);if(n)if(e===-1){n.classList.add(`show`);let e=document.getElementById(`clarifyCustomTextarea`);e&&e.focus()}else n.classList.remove(`show`);i.debug(`[SidePanel] selectclarificationselect :`,e)}function Ha(){if(!z){i.error(`[SidePanel] no has currenttool callID`);return}let e=z.toolCallId,t=z.sessionId,n=-1;document.querySelectorAll(`.clarify-option-item`).forEach((e,t)=>{e.classList.contains(`selected`)&&(n=parseInt(e.dataset.index))});let r=document.getElementById(`clarifyCustomTextarea`),a=r?r.value.trim():``,o=document.getElementById(`clarifyAdditionalTextarea`),s=o?o.value.trim():``,c={type:`CLARIFY_RESPONSE`,toolCallId:e,sessionId:t,selectedOption:n,customInput:a,additionalInfo:s};i.debug(`[SidePanel] send clarificationresponse:`,c),chrome.runtime.sendMessage(c),La()}function Ua(){if(z){let e={type:`CLARIFY_RESPONSE`,toolCallId:z.toolCallId,sessionId:z.sessionId,selectedOption:-1,customInput:``,additionalInfo:``};chrome.runtime.sendMessage(e)}Ba()}function Wa(e){return e?.reason===`timeout`&&e?.defaultOption||null}function Ga(e){i.debug(`[SidePanel] received clarificationtimeoutnotification:`,e);let t=e?.toolCallId;if(!t){if(e?.sessionId&&C.currentClarifySessionId&&e.sessionId!==C.currentClarifySessionId){i.debug(`[SidePanel] clarificationtimeoutfrom othersession,ignore`);return}if(!z)return;Ka(Wa(e));return}if(z&&z.toolCallId===t){Ka(Wa(e));return}let n=ya.findIndex(e=>e.toolCallId===t);n>=0&&(i.debug(`[SidePanel] drop queued clarify (already settled by background):`,t),ya.splice(n,1),ja(),ha(va))}function Ka(e=null){let t=z?.question;La(),P(e?r(`clarify.timedOutDefaulted`,{option:e}):`${r(`clarify.timedOut`)}${t?`:${t}`:``}`,`warning`),Ca(`error`)}ua(va,{present:Na,pendingCount:()=>ya.length,refresh:ja});function qa(){let e=document.getElementById(`clarifyConfirmBtn`);e&&e.addEventListener(`click`,Ha);let t=document.getElementById(`clarifyCancelBtn`);t&&t.addEventListener(`click`,Ua);let n=document.getElementById(`clarifyExtendBtn`);n&&n.addEventListener(`click`,Oa);let r=document.querySelector(`#clarifyContainer .clarify-content`),a=document.querySelector(`#clarifyContainer .clarify-header`);r&&a&&r.addEventListener(`scroll`,()=>{a.classList.toggle(`scrolled`,r.scrollTop>2)}),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_CLARIFY_DIALOG`?(i.debug(`[SidePanel] received clarificationrequested :`,e,`currently activesession:`,C.activeSessionId),za(e.data),n({success:!0})):e.type===`PLAY_NOTIFICATION_SOUND`?(i.debug(`[SidePanel] recei to play soundrequested :`,e),Ca(e.soundType),n({success:!0})):e.type===`CLARIFY_TIMEOUT`?Ga(e):e.type===`CLARIFY_EXTENDED`&&ka(e)}),i.debug(`[SidePanel] clarification dialogeventinitializing`)}var Ja=oa.CONFIRM,Ya=[],Xa=null,Za=null,Qa=null;function $a(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}function eo(){Za&&=(clearInterval(Za),null),Qa&&=(clearTimeout(Qa),null)}function to(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&JSON.stringify(e.args??null)===JSON.stringify(t.args??null)}function no(e){let t=e.message||r(`dialog.confirmAction`,{name:e.toolLabel||e.toolName}),n=Ya.length,i=ga(Ja),a=t;return n>0&&(a+=` ${r(`dialog.pendingQueue`,{count:n})}`),i>0&&(a+=` ${r(`dialog.otherPending`,{count:i})}`),a}function ro(e){let{toolName:t,toolLabel:n,args:a,timeout:o=3e5}=e;C.currentConfirmToolCallId=e.toolCallId,C.currentConfirmSessionId=e.sessionId||null;let s=document.getElementById(`confirmOverlay`);if(!s)return!1;document.getElementById(`confirmToolName`).textContent=n||t;let c=e.variant===`network`,l=document.getElementById(`confirmTitle`);l&&(l.textContent=r(c?`dialog.networkTitle`:`dialog.operationConfirm`));let u=document.getElementById(`confirmApproveLoopBtn`);u&&(u.textContent=r(c?`dialog.approveWhitelist`:`dialog.approveLoop`));let d=document.getElementById(`confirmArgsSummary`);if(d&&a){let e=Object.entries(a).filter(([e,t])=>t!=null&&t!==``).slice(0,5);e.length>0?(d.textContent=``,e.forEach(([e,t],n)=>{n>0&&d.appendChild(document.createTextNode(`、 `));let r=typeof t==`string`?t:JSON.stringify(t),i=r.length>80?r.substring(0,80)+`...`:r,a=document.createElement(`span`);a.className=`confirm-arg`,a.style.marginRight=`8px`,r.length>80&&(a.title=r);let o=document.createElement(`strong`);o.textContent=`${e}:`,a.appendChild(o),a.appendChild(document.createTextNode(` ${i}`)),d.appendChild(a)}),d.style.display=`block`):d.style.display=`none`}let f=document.getElementById(`confirmMessage`);f&&(f.textContent=no(e)),eo();let p=Math.floor(o/1e3),m=document.getElementById(`confirmCountdownText`),h=document.getElementById(`confirmCountdown`);return m&&h&&(h.classList.remove(`warning`),h.style.display=`flex`,m.textContent=r(`dialog.remainingTime`,{time:$a(p)}),Za=setInterval(()=>{if(p--,p<=0){clearInterval(Za),Za=null,m.textContent=r(`dialog.remainingTime`,{time:`0:00`});return}m.textContent=r(`dialog.remainingTime`,{time:$a(p)}),p<=30&&h.classList.add(`warning`)},1e3)),s.style.display=`flex`,Qa=setTimeout(()=>{i.debug(`[SidePanel] confirm dialogtimeout,autodeny`),lo(!1,`single`)},o),!0}function io(){if(Xa)return!0;if(Ya.length===0)return!1;let e=Ya.shift();return ro(e)?(Xa=e,_a(Ja,e),!0):(e.resolve&&e.resolve(!1),!1)}function ao(){let e=document.getElementById(`confirmOverlay`);e&&(e.style.display=`none`);let t=document.getElementById(`confirmCountdown`);t&&(t.classList.remove(`warning`),t.style.display=`none`),C.currentConfirmToolCallId=null,C.currentConfirmSessionId=null}function oo(){if(Ya.length>0){da(Ja);return}ao(),fa(Ja)}function so(e){let t=Xa?.resolve;Xa=null,eo(),t&&t(e),oo()}function co(e){let t={...e,sessionId:e.sessionId||null};return i.debug(`[SidePanel] showconfirm dialog:`,t.toolName,e),Xa&&to(Xa,t)?(i.debug(`[SidePanel] duplicate confirm request, ignored:`,t.toolCallId),Promise.resolve(!1)):Ya.some(e=>to(e,t))?(i.debug(`[SidePanel] queued duplicate confirm, ignored:`,t.toolCallId),Promise.resolve(!1)):new Promise(e=>{Ya.push({...t,resolve:e}),da(Ja),Xa&&uo(),ha(Ja)})}function lo(e,t=`single`){if(!Xa)return;let n=Xa.toolCallId,r=Xa.sessionId;eo(),chrome.runtime.sendMessage({type:`TOOL_CONFIRMATION_RESPONSE`,toolCallId:n,confirmed:e,scope:t,sessionId:r}).catch(e=>{i.debug(`[SidePanel] send confirmationresponse failed:`,e.message)}),so(e)}function uo(){if(!Xa)return;let e=document.getElementById(`confirmMessage`);e&&(e.textContent=no(Xa))}function fo(e){let t=e?.toolCallId;if(!t)return;if(Xa&&Xa.toolCallId===t){i.debug(`[SidePanel] dismiss active confirm dialog (already settled by background):`,t),so(!1);return}let n=Ya.findIndex(e=>e.toolCallId===t);if(n>=0){i.debug(`[SidePanel] drop queued confirm dialog (already settled by background):`,t);let[e]=Ya.splice(n,1);e.resolve&&e.resolve(!1),uo(),ha(Ja)}}ua(Ja,{present:io,pendingCount:()=>Ya.length,refresh:()=>{Xa&&uo()}});function po(){let e=document.getElementById(`confirmApproveOnceBtn`),t=document.getElementById(`confirmApproveLoopBtn`),n=document.getElementById(`confirmDenyBtn`);e&&e.addEventListener(`click`,()=>lo(!0,`single`)),t&&t.addEventListener(`click`,()=>{lo(!0,Xa?.variant===`network`?`whitelist`:`loop`)}),n&&n.addEventListener(`click`,()=>lo(!1,`single`)),chrome.runtime.onMessage.addListener((e,t,n)=>e.type===`SHOW_CONFIRM_DIALOG`?(co(e.data),n({received:!0}),!1):e.type===`DISMISS_CONFIRM_DIALOG`?(fo(e.data),n({received:!0}),!1):!1)}var mo=t({closeCurrentSession:()=>ac,handleDuplicateSession:()=>Xs,handleSessionSwitch:()=>Ys,newSession:()=>xo,renderSessionTabs:()=>yo});n(`zh`,{session:{newSession:`新会话`,closeSession:`关闭会话`,taskCompleted:`任务已完成`,noMatch:`未找到匹配的会话`,rename:`重命名`,duplicate:`复制会话`,confirmCloseMessageWithTitle:`确定要关闭会话 "{title}" 吗?`,confirmCloseAllMessage:`确定要关闭所有 {count} 个会话吗?`,confirmCloseAllTitle:`关闭全部会话`,forkedFrom:`已从 "{title}" 分叉`,forkedSession:`已复制会话 "{title}"`,operationFailed:`操作失败:{message}`,sessionListTitle:`会话列表`,closeGroupAll:`全部关闭`,confirmCloseGroupMessage:`确定要关闭“{group}”下的 {count} 个会话吗?`,today:`今天`,yesterday:`昨天`,last7Days:`近 7 天`,earlier:`更早`,todayFormat:`{hour}:{minute}`,yesterdayFormat:`昨天 {hour}:{minute}`,daysAgo:`{count} 天前`,archive:`归档会话`,archiveEntry:`归档区`,archiveEntryTitle:`查看归档会话`,archivePanelTitle:`归档区`,archiveSearchPlaceholder:`搜索归档会话...`,archiveEmpty:`暂无归档会话`,archiveNoMatch:`未找到匹配的归档会话`,archiveHint:`归档只是移出视野,随时可以恢复`,archiveBusyRunning:`该会话任务还在执行,完成后再归档`,archiveBusyQueued:`该会话还有排队任务,先清空队列再归档`,archived:`已归档到归档区`,archivedRestored:`已恢复会话「{title}」`,archivedAt:`归档于 {time}`,restore:`恢复`,restoreTitle:`恢复到会话列表`,deleteForever:`彻底删除`,confirmDeleteForeverTitle:`彻底删除会话`,confirmDeleteForeverMessage:`「{title}」将被彻底删除,消息与执行记录都无法恢复。确定继续吗?`,archiveDeleted:`已彻底删除会话「{title}」`,backToSessionList:`返回会话列表`,expandSidebar:`展开会话列表`,collapseSidebar:`收起会话列表`,searchSessions:`搜索会话`,sortModeTitle:`会话排序`,sortManual:`手动排序(拖拽调整,与标签栏一致)`,sortRecent:`最近更新优先(按时间倒序,带时间分组)`}}),n(`en`,{session:{newSession:`New Session`,closeSession:`Close Session`,taskCompleted:`Task completed`,noMatch:`No matching sessions found`,rename:`Rename`,duplicate:`Duplicate`,confirmCloseMessageWithTitle:`Are you sure you want to close session "{title}"?`,confirmCloseAllMessage:`Are you sure you want to close all {count} sessions?`,confirmCloseAllTitle:`Close All Sessions`,forkedFrom:`Forked from "{title}"`,forkedSession:`Duplicated session "{title}"`,operationFailed:`Operation failed: {message}`,sessionListTitle:`Sessions`,closeGroupAll:`Close all`,confirmCloseGroupMessage:`Are you sure you want to close {count} sessions in "{group}"?`,today:`Today`,yesterday:`Yesterday`,last7Days:`Last 7 days`,earlier:`Earlier`,todayFormat:`{hour}:{minute}`,yesterdayFormat:`Yesterday {hour}:{minute}`,daysAgo:`{count}d ago`,archive:`Archive session`,archiveEntry:`Archived`,archiveEntryTitle:`View archived sessions`,archivePanelTitle:`Archived sessions`,archiveSearchPlaceholder:`Search archived sessions...`,archiveEmpty:`No archived sessions`,archiveNoMatch:`No archived sessions found`,archiveHint:`Archiving only hides a session — you can restore it anytime`,archiveBusyRunning:`This session is still running. Archive it when it finishes`,archiveBusyQueued:`This session still has queued tasks. Clear the queue first`,archived:`Moved to archive`,archivedRestored:`Session "{title}" restored`,archivedAt:`Archived {time}`,restore:`Restore`,restoreTitle:`Restore to session list`,deleteForever:`Delete permanently`,confirmDeleteForeverTitle:`Delete session permanently`,confirmDeleteForeverMessage:`"{title}" will be permanently deleted. Messages and execution logs cannot be recovered. Continue?`,archiveDeleted:`Session "{title}" permanently deleted`,backToSessionList:`Back to sessions`,expandSidebar:`Expand session list`,collapseSidebar:`Collapse session list`,searchSessions:`Search sessions`,sortModeTitle:`Session order`,sortManual:`Manual order (drag to arrange, same as tabs)`,sortRecent:`Most recent first (time order with day groups)`}});var B={visible:!1,highlightIndex:-1,filteredSessions:[]},ho={draggedId:null,sourceType:null};function go(e){if(!e)return``;let t=new Date(e),n=new Date,i=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),a=t.getTime();if(a>=i)return r(`session.todayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});if(a>=i-864e5)return r(`session.yesterdayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});let o=Math.floor((i-a)/864e5);return o<=7?r(`session.daysAgo`,{count:o}):t.getFullYear()===n.getFullYear()?`${t.getMonth()+1}/${t.getDate()}`:`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()}`}function _o(e){return e.sort((e,t)=>{let n=e.updatedAt?new Date(e.updatedAt).getTime():0;return(t.updatedAt?new Date(t.updatedAt).getTime():0)-n})}function vo(e){if(!e)return`earlier`;let t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),i=t.getTime();return i>=r?`today`:i>=r-864e5?`yesterday`:Math.floor((r-i)/864e5)<=7?`last7Days`:`earlier`}async function yo(e=null){let t=e||await ti({withActiveHistory:!1});C.sessions=t.list,C.activeSessionId=t.activeSessionId;let n=document.getElementById(`sessionTabs`),i=document.getElementById(`sessionTabsScroll`),a=document.getElementById(`sessionTabsActions`);!n||!i||!a||(i.style.opacity=``,i.innerHTML=``,t.list.forEach(e=>{let t=document.createElement(`div`);t.className=`session-tab`,t.dataset.sessionId=e.id,e.id===C.activeSessionId&&t.classList.add(`active`),t.title=e.title;let n=document.createElement(`span`);n.className=`session-tab-title`,n.textContent=e.title||r(`session.newSession`),t.appendChild(n);let a=document.createElement(`span`);if(a.className=`session-tab-close`,a.innerHTML=`✕`,a.title=r(`session.closeSession`),a.addEventListener(`click`,async t=>{if(t.stopPropagation(),(e.id===C.activeSessionId?C.messageHistory?.length||0:e.messageCount??e.messageHistory?.length??0)===0){Jo(await qo(e.id)),await ic();return}tc(e,async()=>{await ic()})}),t.appendChild(a),e.isGenerating||C.generatingSessionIds.has(e.id)){let e=document.createElement(`span`);e.className=`session-tab-indicator`,t.appendChild(e)}else if(C.completedSessionIds.has(e.id)&&e.id!==C.activeSessionId){let e=document.createElement(`span`);e.className=`session-tab-completed-indicator`,e.title=r(`session.taskCompleted`),t.appendChild(e)}let o=fr(e.id);if(o>0){let e=document.createElement(`span`);e.className=`session-tab-queue-badge`,e.textContent=String(o>99?`99+`:o),e.title=r(`queue.badgeTitle`,{count:o}),t.appendChild(e)}t.addEventListener(`click`,async n=>{if(n.preventDefault(),e.id!==C.activeSessionId&&!Gs){Gs=!0,i.querySelectorAll(`.session-tab.active`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`);try{await Ys(e.id)}finally{Gs=!1,C.activeSessionId!==e.id&&yo({list:C.sessions,activeSessionId:C.activeSessionId})}}}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),nc(t,e)}),t.addEventListener(`mousedown`,async t=>{t.button===1&&(t.preventDefault(),t.stopPropagation(),Jo(await qo(e.id)),await ic())}),t.draggable=!0,t.addEventListener(`dragstart`,t=>Ao(t,e.id)),t.addEventListener(`dragover`,e=>jo(e)),t.addEventListener(`dragleave`,e=>Mo(e)),t.addEventListener(`drop`,t=>No(t,e.id)),t.addEventListener(`dragend`,e=>Po(e)),i.appendChild(t)}),bo(),So(),Qo(),Ws(),$s(i),To(i),Eo(i),ko(i),Cs(),As())}function bo(){let e=document.getElementById(`sessionTabsMore`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,e=>{e.stopPropagation(),vs()})}async function xo(){let e=C.activeSessionId;await ni();let t=await ai();C.activeSessionId=t.id,C.messageHistory=[],C.activeCompaction=null,ri(t),document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:t.id,previousSessionId:e}})),yo()}function So(){let e=document.getElementById(`sessionTabsAdd`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,()=>xo())}var Co=0,wo=0;function To(e){let t=document.getElementById(`sessionTabsMore`);if(!t)return;if(!fs()){t.style.display=`none`;return}let n=e.scrollWidth>e.clientWidth;t.style.display=n||Co>0?`flex`:`none`}async function Eo(e){let t=++wo,n;try{n=await di()}catch{return}t===wo&&(Co=n.length,To(e))}var Do=null;function Oo(){if(Do)return;let e=document.getElementById(`sessionTabsScroll`);e&&(Do=new ResizeObserver(()=>{requestAnimationFrame(()=>{To(e)})}),Do.observe(e))}function ko(e){let t=e.querySelector(`.session-tab.active`);if(t){let n=t.offsetLeft,r=t.offsetWidth;e.scrollLeft=n-(e.clientWidth-r)/2}e.style.opacity=`1`}function Ao(e,t){ho.draggedId=t,ho.sourceType=`tab`,e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),e.currentTarget.classList.add(`dragging`)}function jo(e){e.preventDefault(),e.dataTransfer.dropEffect=`move`,e.currentTarget.classList.add(`drag-over`)}function Mo(e){e.currentTarget.classList.remove(`drag-over`)}async function No(e,t){e.preventDefault(),e.currentTarget.classList.remove(`drag-over`);let n=ho.draggedId;if(!n||n===t)return;let r=C.sessions||[],i=r.findIndex(e=>e.id===n),a=r.findIndex(e=>e.id===t);if(i===-1||a===-1)return;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s),C.sessions=o,await li(o.map(e=>e.id)),yo()}function Po(e){e.currentTarget.classList.remove(`dragging`),document.querySelectorAll(`.session-tab.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),ho.draggedId=null,ho.sourceType=null}function Fo(){B.visible?Lo():Io()}async function Io(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);if(!e||!t)return;let n=await ti();C.sessions=n.list,C.activeSessionId=n.activeSessionId,B.filteredSessions=_o([...n.list]),B.highlightIndex=-1,B.visible=!0,Is(),zo(),t.classList.add(`show`);let r=document.getElementById(`sessionDropdownCloseBtn`);r&&(r.onclick=()=>Lo());let i=document.getElementById(`sessionDropdownSearch`),a=document.getElementById(`sessionDropdownSearchClear`);i&&(i.value=B.lastSearchText||``,Ro(),B.lastSearchText&&Go(B.lastSearchText),setTimeout(()=>i.focus(),50),i.oninput=()=>{B.lastSearchText=i.value,Ro(),Go(i.value)},i.onkeydown=e=>{$o(e)}),a&&(a.onclick=()=>{i&&(i.value=``,B.lastSearchText=``,Ro(),Go(``),i.focus())}),e.classList.add(`active`)}function Lo(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);t&&t.classList.remove(`show`),e&&e.classList.remove(`active`);let n=document.getElementById(`sessionDropdownSearch`);n&&(B.lastSearchText=n.value,n.oninput=null,n.onkeydown=null);let r=document.getElementById(`sessionDropdownSearchClear`);r&&(r.onclick=null),B.visible=!1,B.highlightIndex=-1,B.filteredSessions=[]}function Ro(){let e=document.getElementById(`sessionDropdownSearch`),t=document.getElementById(`sessionDropdownSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function zo(){Bo({listEl:document.getElementById(`sessionDropdownList`),filteredSessions:B.filteredSessions,highlightIndex:B.highlightIndex,onSelect:e=>Ko(e)})}function Bo({listEl:e,filteredSessions:t,highlightIndex:n,onSelect:i,grouped:a=!0,draggable:o=!1}){if(!e)return;if(e.innerHTML=``,t.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(`session.noMatch`),e.appendChild(t);return}let s={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},c={};a&&t.forEach(e=>{let t=vo(e.updatedAt);c[t]=(c[t]||0)+1});let l=null;t.forEach((t,u)=>{if(a){let n=vo(t.updatedAt);if(n!==l){l=n;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let i=document.createElement(`span`);if(i.textContent=s[n]||n,t.appendChild(i),(c[n]||0)>0){let e=document.createElement(`button`);e.className=`session-dropdown-group-close`,e.textContent=r(`session.closeGroupAll`),e.onclick=e=>{e.stopPropagation(),Zo(n,s[n]||n)},t.appendChild(e)}e.appendChild(t)}}let d=Wo(t,{index:u,highlightIndex:n,onSelect:i});o&&Ho(d,t.id),e.appendChild(d)})}var Vo=null;function Ho(e,t){e.draggable=!0,e.classList.add(`draggable`),e.addEventListener(`dragstart`,n=>{Vo=t,n.dataTransfer.effectAllowed=`move`,n.dataTransfer.setData(`text/plain`,t),e.classList.add(`dragging`)}),e.addEventListener(`dragover`,n=>{!Vo||Vo===t||(n.preventDefault(),n.dataTransfer.dropEffect=`move`,e.classList.add(`drag-over`))}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drag-over`)),e.addEventListener(`drop`,n=>{n.preventDefault(),n.stopPropagation(),e.classList.remove(`drag-over`),Uo(Vo,t)}),e.addEventListener(`dragend`,()=>{e.classList.remove(`dragging`),document.querySelectorAll(`.session-dropdown-item.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),Vo=null})}async function Uo(e,t){let n=e;if(Vo=null,!n||n===t)return;let r=C.sessions||[],i=r.findIndex(e=>e.id===n),a=r.findIndex(e=>e.id===t);if(i===-1||a===-1)return;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s),C.sessions=o,await li(o.map(e=>e.id)),await yo()}function Wo(e,{index:t,highlightIndex:n,onSelect:i}){let a=document.createElement(`div`);a.className=`session-dropdown-item`,a.dataset.sessionId=e.id,a.dataset.index=t,e.id===C.activeSessionId&&a.classList.add(`active`),t===n&&a.classList.add(`highlighted`);let o=e.isGenerating||C.generatingSessionIds.has(e.id);if(C.completedSessionIds.has(e.id)&&e.id!==C.activeSessionId&&!o){let e=document.createElement(`span`);e.className=`session-dropdown-item-completed`,e.title=r(`session.taskCompleted`),a.appendChild(e)}let s=fr(e.id);if(s>0){let e=document.createElement(`span`);e.className=`session-dropdown-item-queue`,e.textContent=String(s>99?`99+`:s),e.title=r(`queue.badgeTitle`,{count:s}),a.appendChild(e)}let c=document.createElement(`span`);if(c.className=`session-dropdown-item-icon`,o){let e=document.createElement(`span`);e.className=`session-dropdown-item-running`,c.appendChild(e)}else c.innerHTML=`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`;a.appendChild(c);let l=document.createElement(`span`);if(l.className=`session-dropdown-item-title`,l.textContent=e.title||r(`session.newSession`),l.title=e.title||r(`session.newSession`),a.appendChild(l),e.id===C.activeSessionId){let e=document.createElement(`span`);e.className=`session-dropdown-item-check`,e.innerHTML=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`,a.appendChild(e)}let u=document.createElement(`span`);u.className=`session-dropdown-item-time`,u.textContent=go(e.updatedAt),a.appendChild(u);let d=document.createElement(`span`);d.className=`session-dropdown-item-actions`;let f=document.createElement(`span`);f.className=`session-dropdown-item-rename`,f.title=r(`session.rename`),f.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,f.addEventListener(`click`,t=>{t.stopPropagation(),t.preventDefault(),ec(e)}),d.appendChild(f);let p=document.createElement(`span`);p.className=`session-dropdown-item-duplicate`,p.title=r(`session.duplicate`),p.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,p.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await Xs(e.id);let n=await ti({withActiveHistory:!1});C.sessions=n.list,C.activeSessionId=n.activeSessionId,Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}),d.appendChild(p);let m=document.createElement(`span`);m.className=`session-dropdown-item-archive`,m.title=r(`session.archive`),m.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,m.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await Ps(e.id),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}),d.appendChild(m);let h=document.createElement(`span`);return h.className=`session-dropdown-item-close`,h.innerHTML=`✕`,h.title=r(`session.closeSession`),h.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await Yo(e.id)}),d.appendChild(h),a.appendChild(d),a.addEventListener(`click`,async t=>{t.preventDefault(),await i(e.id)}),a}function Go(e){let t=C.sessions||[],n;if(!e.trim())n=[...t];else{let i=e.trim().toLowerCase();n=t.filter(e=>(e.title||r(`session.newSession`)).toLowerCase().includes(i))}B.filteredSessions=_o(n),B.highlightIndex=-1,zo()}async function Ko(e){Lo(),e!==C.activeSessionId&&await Ys(e)}async function qo(e){let t=fr(e)+ur(e).length;return await si(e),t}function Jo(e){e<=0||P(r(`queue.sessionDropped`,{count:e}),`info`,3e3)}async function Yo(e){let t=(C.sessions||[]).find(t=>t.id===e);t&&((e===C.activeSessionId?C.messageHistory?.length||0:t.messageCount??t.messageHistory?.length??0)>0&&!await js(r(`session.confirmCloseMessageWithTitle`,{title:t.title}),r(`session.closeSession`))||(Jo(await qo(e)),await ic(),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)))}async function Xo(){let e=C.sessions||[];if(e.length===0||!await js(r(`session.confirmCloseAllMessage`,{count:e.length}),r(`session.confirmCloseAllTitle`)))return;let t=0;for(let n of e)t+=await qo(n.id);Jo(t),await ic(),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}async function Zo(e,t){let n=(C.sessions||[]).filter(t=>vo(t.updatedAt)===e);if(n.length===0||!await js(r(`session.confirmCloseGroupMessage`,{group:t,count:n.length}),r(`session.closeSession`)))return;let i=0;for(let e of n)i+=await qo(e.id);Jo(i),await ic(),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}function Qo(){let e=document.getElementById(`sessionDropdownCloseAll`),t=document.getElementById(`sessionDropdown`);if(t){if(e){let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,async e=>{e.stopPropagation(),await Xo()})}t.addEventListener(`click`,e=>{e.stopPropagation()})}}function $o(e){if(!B.visible)return;let t=B.filteredSessions.length;if(t===0){e.key===`Escape`&&Lo();return}switch(e.key){case`ArrowDown`:e.preventDefault(),B.highlightIndex=Math.min(B.highlightIndex+1,t-1),zo(),es(document.getElementById(`sessionDropdownList`));break;case`ArrowUp`:e.preventDefault(),B.highlightIndex=Math.max(B.highlightIndex-1,0),zo(),es(document.getElementById(`sessionDropdownList`));break;case`Enter`:if(e.preventDefault(),B.highlightIndex>=0&&B.highlightIndex<t){let e=B.filteredSessions[B.highlightIndex];Ko(e.id)}break;case`Escape`:e.preventDefault(),Lo();break}}function es(e){let t=(e||document).querySelector(`.session-dropdown-item.highlighted`);t&&t.scrollIntoView({block:`nearest`})}var ts=560,ns=200,rs=480,is=360,as=240,os=`sessionSidebarExpanded`,ss=`sessionSidebarWidth`,cs=`sessionSidebarSortMode`,ls=`manual`,us=`recent`,V={expanded:!1,width:as,sortMode:ls,narrow:!1,pendingRestore:!1,highlightIndex:-1,filteredSessions:[],inited:!1,lastActiveId:null};function ds(e){let t=document.getElementById(`mainRow`),n=t?Math.max(ns,t.clientWidth-is):rs;return Math.max(ns,Math.min(e,rs,n))}function fs(){let e=document.getElementById(`mainRow`);return e?e.clientWidth<ts:!0}function ps(){let e=document.getElementById(`sessionSidebar`);if(!e)return;V.narrow=fs(),e.classList.toggle(`sidebar-hidden`,V.narrow),e.classList.toggle(`expanded`,!V.narrow&&V.expanded),e.style.setProperty(`--session-sidebar-width`,`${V.width}px`),ms();let t=document.getElementById(`sessionSidebarToggle`);t&&t.classList.toggle(`sidebar-hidden`,V.narrow||V.expanded);let n=document.getElementById(`sessionTabs`);if(n){let e=!V.narrow&&V.expanded;if(n.classList.toggle(`tabs-hidden`,e),!e){let e=document.getElementById(`sessionTabsScroll`);e&&ko(e)}}}function ms(){let e=!V.narrow&&V.expanded?V.width:0;document.body.style.setProperty(`--session-sidebar-offset`,`${e}px`)}async function hs(){try{await chrome.storage.local.set({[os]:V.expanded,[ss]:V.width,[cs]:V.sortMode})}catch{}}function gs(){fs()||(V.expanded=!0,ps(),hs(),Cs())}function _s(){V.expanded=!1,ps(),hs()}function vs(){if(fs()){Fo();return}V.expanded?_s():gs()}function ys(){let e=document.getElementById(`sessionSidebarList`),t=V.sortMode===us,n=!!(document.getElementById(`sessionSidebarSearch`)?.value||``).trim();Bo({listEl:e,filteredSessions:V.filteredSessions,highlightIndex:V.highlightIndex,onSelect:e=>ws(e),grouped:t,draggable:!t&&!n});let r=C.activeSessionId;r&&V.lastActiveId!==r&&(V.lastActiveId=r,e?.querySelector(`.session-dropdown-item.active`)?.scrollIntoView({block:`nearest`}))}function bs(e){let t=C.sessions||[],n;if(!e.trim())n=[...t];else{let i=e.trim().toLowerCase();n=t.filter(e=>(e.title||r(`session.newSession`)).toLowerCase().includes(i))}V.filteredSessions=V.sortMode===us?_o(n):n.reverse(),V.highlightIndex=-1,ys()}function xs(){document.querySelectorAll(`.session-sidebar-sort-btn`).forEach(e=>{let t=e.dataset.mode===V.sortMode;e.classList.toggle(`active`,t),e.setAttribute(`aria-pressed`,t?`true`:`false`)})}function Ss(e){e!==ls&&e!==us||V.sortMode!==e&&(V.sortMode=e,xs(),V.lastActiveId=null,bs(document.getElementById(`sessionSidebarSearch`)?.value||``),hs())}function Cs(){let e=document.getElementById(`sessionSidebar`);!e||!e.classList.contains(`expanded`)||bs(document.getElementById(`sessionSidebarSearch`)?.value||``)}async function ws(e){e!==C.activeSessionId&&await Ys(e)}function Ts(e){let t=V.filteredSessions,n=t.length;if(n===0){e.key===`Escape`&&_s();return}switch(e.key){case`ArrowDown`:e.preventDefault(),V.highlightIndex=Math.min(V.highlightIndex+1,n-1),ys(),es(document.getElementById(`sessionSidebarList`));break;case`ArrowUp`:e.preventDefault(),V.highlightIndex=Math.max(V.highlightIndex-1,0),ys(),es(document.getElementById(`sessionSidebarList`));break;case`Enter`:e.preventDefault(),V.highlightIndex>=0&&V.highlightIndex<n&&ws(t[V.highlightIndex].id);break;case`Escape`:e.preventDefault(),_s();break}}function Es(){let e=document.getElementById(`sessionSidebarSearch`),t=document.getElementById(`sessionSidebarSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function Ds(){let e=document.getElementById(`sessionSidebar`),t=document.getElementById(`sessionSidebarGrip`);!e||!t||t.addEventListener(`mousedown`,t=>{t.preventDefault();let n=t.clientX,r=V.width;e.classList.add(`resizing`);function i(t){let i=ds(r+(t.clientX-n));V.width=i,e.style.setProperty(`--session-sidebar-width`,`${i}px`),ms()}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),hs()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function Os(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{requestAnimationFrame(()=>{let e=fs();e!==V.narrow&&(e&&V.expanded?V.pendingRestore=!0:!e&&V.pendingRestore&&(V.pendingRestore=!1),ps(),!e&&V.expanded&&Cs())})}).observe(e)}function ks(){fs()?Io():gs()}async function As(){if(V.inited||!document.getElementById(`sessionSidebar`))return;V.inited=!0;try{let e=await chrome.storage.local.get([os,ss,cs]);V.expanded=e[os]===!0,typeof e[ss]==`number`&&(V.width=ds(e[ss])),(e[cs]===us||e[cs]===ls)&&(V.sortMode=e[cs])}catch{}xs(),fs()&&V.expanded&&(V.pendingRestore=!0),ps(),Cs(),document.getElementById(`sessionSidebarToggle`)?.addEventListener(`click`,()=>vs()),document.getElementById(`sessionSidebarAdd`)?.addEventListener(`click`,()=>{xo()}),document.getElementById(`sessionSidebarCollapse`)?.addEventListener(`click`,()=>_s()),document.querySelectorAll(`.session-sidebar-sort-btn`).forEach(e=>{e.addEventListener(`click`,()=>Ss(e.dataset.mode))}),document.getElementById(`sessionSidebarArchiveEntry`)?.addEventListener(`click`,()=>{Ls()}),document.getElementById(`sessionSidebarCloseAll`)?.addEventListener(`click`,async e=>{e.stopPropagation(),await Xo()});let e=document.getElementById(`sessionSidebarSearch`),t=document.getElementById(`sessionSidebarSearchClear`);e&&(e.addEventListener(`input`,()=>{Es(),bs(e.value)}),e.addEventListener(`keydown`,e=>{Ts(e)})),t&&t.addEventListener(`click`,()=>{e&&(e.value=``,Es(),bs(``),e.focus())}),Ds(),Os(),Is()}function js(e,t){return new Promise(t=>{let n=document.getElementById(`sessionDeleteModal`),r=document.getElementById(`sessionDeleteMessage`),i=document.getElementById(`sessionDeleteConfirmBtn`),a=document.getElementById(`sessionDeleteCancelBtn`),o=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!r){t(!1);return}r.textContent=e;let s=()=>{n.classList.remove(`show`),i.removeEventListener(`click`,c),a.removeEventListener(`click`,l),o.removeEventListener(`click`,l)},c=()=>{s(),t(!0)},l=()=>{s(),t(!1)};i.addEventListener(`click`,c),a.addEventListener(`click`,l),o.addEventListener(`click`,l),n.classList.add(`show`)})}var Ms=``,Ns=!1;async function Ps(e){if(!e)return;let t=fi(e);if(!t.ok){t.reason===`running`?P(r(`session.archiveBusyRunning`),`warning`):t.reason===`queued`&&P(r(`session.archiveBusyQueued`),`warning`);return}let n=e===C.activeSessionId,i=await pi(e);if(!i?.ok){i?.reason===`running`?P(r(`session.archiveBusyRunning`),`warning`):i?.reason===`queued`?P(r(`session.archiveBusyQueued`),`warning`):P(r(`session.operationFailed`,{message:i?.reason||`unknown`}),`error`);return}if(document.dispatchEvent(new CustomEvent(`session-archived`,{detail:{sessionId:e}})),n)await Fs(e);else{let e=await ti();C.sessions=e.list,yo(e)}await Is(),P(r(`session.archived`),`info`)}async function Fs(e){let t=_o([...(await ti()).list]).filter(t=>t.id!==e);if(t.length>0){await Ys(t[0].id);return}await ai(),await ic()}async function Is(){let e=[`sessionArchiveEntryLabel`,`sessionSidebarArchiveLabel`].map(e=>document.getElementById(e));if(!e.some(Boolean))return;Co=(await di()).length;let t=document.getElementById(`sessionTabsScroll`);t&&To(t);let n=r(`session.archiveEntry`);e.forEach(e=>{e&&(e.textContent=n)})}async function Ls(){let e=document.getElementById(`sessionArchivePanel`);if(!e)return;Ws(),Ms=``;let t=document.getElementById(`sessionArchiveSearch`);t&&(t.value=``),zs(),await Bs(),e.classList.add(`show`),Lo()}function Rs(){let e=document.getElementById(`sessionArchivePanel`);e&&e.classList.remove(`show`)}function zs(){let e=document.getElementById(`sessionArchiveSearchClear`);e&&(e.style.display=Ms?`flex`:`none`)}async function Bs(){let e=document.getElementById(`sessionArchiveList`);if(!e)return;let t=await di(),n=Ms.trim().toLowerCase(),i=n?t.filter(e=>(e.title||``).toLowerCase().includes(n)):t;if(e.innerHTML=``,i.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(n?`session.archiveNoMatch`:`session.archiveEmpty`),e.appendChild(t);return}let a={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},o=null;i.forEach(t=>{let n=vo(t.archivedAt);if(n!==o){o=n;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let r=document.createElement(`span`);r.textContent=a[n]||n,t.appendChild(r),e.appendChild(t)}e.appendChild(Vs(t))})}function Vs(e){let t=document.createElement(`div`);t.className=`session-dropdown-item session-archive-item`,t.dataset.sessionId=e.id,t.title=e.title||r(`session.newSession`);let n=document.createElement(`span`);n.className=`session-dropdown-item-icon`,n.innerHTML=`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,t.appendChild(n);let i=document.createElement(`span`);i.className=`session-dropdown-item-title`,i.textContent=e.title||r(`session.newSession`),t.appendChild(i);let a=document.createElement(`span`);a.className=`session-dropdown-item-time`,a.textContent=r(`session.archivedAt`,{time:go(e.archivedAt)}),t.appendChild(a);let o=document.createElement(`span`);o.className=`session-dropdown-item-actions`;let s=document.createElement(`span`);s.className=`session-dropdown-item-restore`,s.title=r(`session.restoreTitle`),s.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 14 4 9 9 4"/><path d="M20 20v-7a4 4 0 0 0-4-4H4"/></svg>`,s.addEventListener(`click`,async t=>{t.stopPropagation(),await Hs(e.id)}),o.appendChild(s);let c=document.createElement(`span`);return c.className=`session-dropdown-item-delete`,c.title=r(`session.deleteForever`),c.innerHTML=`✕`,c.addEventListener(`click`,async t=>{t.stopPropagation(),await Us(e)}),o.appendChild(c),t.appendChild(o),t.addEventListener(`click`,async()=>{await Hs(e.id,{enter:!0})}),t}async function Hs(e,{enter:t=!1}={}){if(!await mi(e)){P(r(`session.operationFailed`,{message:`not found`}),`error`),await Bs();return}let n=await ti();C.sessions=n.list;let i=n.list.find(t=>t.id===e)?.title||r(`session.newSession`);Rs(),await Bs(),await Is(),t?await Ys(e):yo(n),P(r(`session.archivedRestored`,{title:i}),`success`)}async function Us(e){let t=e.title||r(`session.newSession`);await js(r(`session.confirmDeleteForeverMessage`,{title:t}),r(`session.confirmDeleteForeverTitle`))&&(await hi(e.id),await Bs(),await Is(),document.dispatchEvent(new CustomEvent(`session-deleted`,{detail:{sessionId:e.id}})),P(r(`session.archiveDeleted`,{title:t}),`success`))}function Ws(){if(Ns)return;let e=document.getElementById(`sessionArchivePanel`),t=document.getElementById(`sessionArchiveEntry`);if(!e||!t)return;Ns=!0,t.addEventListener(`click`,()=>{Ls()});let n=document.getElementById(`sessionArchiveBackBtn`);n&&n.addEventListener(`click`,()=>{Rs(),ks()});let r=document.getElementById(`sessionArchiveCloseBtn`);r&&r.addEventListener(`click`,()=>Rs());let i=document.getElementById(`sessionArchiveSearch`),a=document.getElementById(`sessionArchiveSearchClear`);i&&(i.addEventListener(`input`,()=>{Ms=i.value,zs(),Bs()}),i.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),Rs(),ks())})),a&&a.addEventListener(`click`,()=>{i&&(i.value=``,Ms=``,zs(),Bs(),i.focus())}),document.addEventListener(`session-archived`,()=>{e.classList.contains(`show`)&&Bs()}),document.addEventListener(`session-deleted`,()=>{e.classList.contains(`show`)&&Bs()})}var Gs=!1,Ks=500;function qs(e){let t=`scrollPosition_${e||`default`}`;chrome.storage.local.get([t],e=>{let n=document.getElementById(`chatContainer`);n&&e[t]!==void 0&&(n.scrollTop=e[t]),A(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>SS);return{updateScrollButtonState:e}},void 0).then(({updateScrollButtonState:e})=>e()).catch(()=>{})})}function Js(e,t){setTimeout(()=>{C.activeSessionId===e&&(He(t)||qs(e))},Ks)}async function Ys(e,{focusMessageId:t=null}={}){let n=C.activeSessionId;if(!await oi(e))return;let r=`agentEnabledTools_${C.activeAgentId||`default`}`,i=`agentMcpClosedServers_${C.activeAgentId||`default`}`,[a,o,s,c]=await Promise.all([ti(),chrome.storage.local.get([i,`ragTools`,`ragToolsIntroduced`]),chrome.storage.local.get([r,`enabledTools`]),C.activeAgentId?ft(C.activeAgentId):Promise.resolve(null)]);C.sessions=a.list,C.activeSessionId=e;let l=o.ragTools||[];C.mcpClosedServers=o[i]||[];let u=!!s[r],d=s[r]||s.enabledTools;if(u||d&&d.length>0){let e=ta(l),t=d.filter(t=>e.has(t));if(u)C.enabledTools=t;else{let e=f.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);C.enabledTools=[...t,...e]}let n=ea(C.enabledTools,l,o.ragToolsIntroduced);C.enabledTools=n.tools,C.enabledTools.length!==d.length&&chrome.storage.local.set({[r]:C.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{C.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let e=ea(C.enabledTools,l,o.ragToolsIntroduced);C.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[r]:C.enabledTools})}C.activeAgentToolIds=c?c.toolIds:null,C.activeAgentMcpExcludedServerIds=c?c.mcpExcludedServerIds??null:null,document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,...t?{skipScrollRestore:!0}:{}}})),ei(e),yo(a),Zs(),XT();try{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await A(async()=>{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await Promise.resolve().then(()=>zm);return{refreshBookmarkPanel:e,updateBookmarkButtons:t}},void 0);e(),setTimeout(()=>t(),100)}catch{}let p=document.getElementById(`toolsPopupOverlay`);p&&p.classList.contains(`show`)&&(Bi(),Ji(),Yi()),Qi(),t&&Js(e,t)}async function Xs(e,t=null){if(e)try{let n=await vi(e,t);await Ys(n.id),P(r(t?`session.forkedFrom`:`session.forkedSession`,{title:n.title}),`success`)}catch(e){i.error(`[SessionUI] copy/forksession failed:`,e),P(r(`session.operationFailed`,{message:e.message}),`error`)}}function Zs(){let e=document.querySelector(`.model-display`);e&&C.currentModel&&(e.textContent=C.currentModel);let t=document.getElementById(`enableToolsBtn`);t&&(t.checked=C.useTools);let n=document.getElementById(`tempIconValue`);n&&C.temperature!==void 0&&(n.textContent=C.temperature.toFixed(2))}var Qs=new WeakSet;function $s(e){Qs.has(e)||(Qs.add(e),e.addEventListener(`wheel`,t=>{e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY)},{passive:!1}))}function ec(e){let t=document.getElementById(`sessionRenameModal`),n=document.getElementById(`sessionRenameInput`),r=document.getElementById(`sessionRenameConfirmBtn`),i=document.getElementById(`sessionRenameCancelBtn`),a=document.getElementById(`sessionRenameCloseBtn`);if(!t||!n)return;n.value=e.title;let o=()=>{t.classList.remove(`show`),r.removeEventListener(`click`,s),i.removeEventListener(`click`,c),a.removeEventListener(`click`,c)},s=async()=>{let t=n.value.trim();if(t&&t!==e.title){await ci(e.id,t),yo();let n=await ti();C.sessions=n.list,C.activeSessionId=n.activeSessionId,Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}o()},c=()=>{o()};r.addEventListener(`click`,s),i.addEventListener(`click`,c),a.addEventListener(`click`,c),n.onkeydown=e=>{e.key===`Enter`?s():e.key===`Escape`&&c()},t.classList.add(`show`),setTimeout(()=>{n.focus(),n.select()},50)}function tc(e,t){let n=document.getElementById(`sessionDeleteModal`),i=document.getElementById(`sessionDeleteMessage`),a=document.getElementById(`sessionDeleteConfirmBtn`),o=document.getElementById(`sessionDeleteCancelBtn`),s=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!i)return;i.textContent=r(`session.confirmCloseMessageWithTitle`,{title:e.title});let c=()=>{n.classList.remove(`show`),a.removeEventListener(`click`,l),o.removeEventListener(`click`,u),s.removeEventListener(`click`,u)},l=async()=>{Jo(await qo(e.id)),t&&await t(),c()},u=()=>{c()};a.addEventListener(`click`,l),o.addEventListener(`click`,u),s.addEventListener(`click`,u),n.classList.add(`show`),requestAnimationFrame(()=>a.focus())}function nc(e,t){let n=document.querySelector(`.session-context-menu`);n&&n.remove();let i=document.createElement(`div`);i.className=`session-context-menu`,i.style.left=e.clientX+`px`,i.style.top=e.clientY+`px`;let a=rc(r(`session.rename`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,()=>{i.remove(),ec(t)});i.appendChild(a);let o=rc(r(`session.duplicate`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,()=>{i.remove(),Xs(t.id)});i.appendChild(o);let s=rc(r(`session.archive`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,async()=>{i.remove(),await Ps(t.id)});i.appendChild(s);let c=rc(r(`session.closeSession`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,async()=>{if(i.remove(),(t.id===C.activeSessionId?C.messageHistory?.length||0:t.messageCount??t.messageHistory?.length??0)===0){Jo(await qo(t.id)),await ic();return}tc(t,async()=>{await ic()})},`danger`);i.appendChild(c),document.body.appendChild(i);let l=e=>{i.contains(e.target)||(i.remove(),document.removeEventListener(`click`,l))};setTimeout(()=>document.addEventListener(`click`,l),0)}function rc(e,t=``,n,r=``){let i=document.createElement(`div`);return i.className=`session-context-menu-item `+r,t?i.innerHTML=`${t}<span>${e}</span>`:i.textContent=e,i.addEventListener(`click`,n),i}async function ic(){let e=C.activeSessionId,t=await ti();t.activeSessionId||(await ai(),t=await ti()),C.activeSessionId=t.activeSessionId,C.sessions=t.list;let n=t.list.find(e=>e.id===t.activeSessionId);if(C.messageHistory=n&&n.messageHistory||[],C.activeCompaction=n?.contextCompaction||null,ri(n),C.activeAgentId=n&&n.agentId||null,C.activeAgentId){let e=await ft(C.activeAgentId);C.activeAgentToolIds=e?e.toolIds:null,C.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null}else C.activeAgentToolIds=null,C.activeAgentMcpExcludedServerIds=null;document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:C.activeSessionId,previousSessionId:e}})),yo(),await XT()}async function ac(){let e=C.activeSessionId;if(!e)return;let t=C.sessions?.find(t=>t.id===e);if(t){if((C.messageHistory?.length||0)===0){Jo(await qo(e)),await ic();return}tc(t,async()=>{await ic()})}}document.addEventListener(`generating-state-changed`,()=>{yo()}),document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{Oo(),As()}):(Oo(),As()),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`].join(``),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M12.146.146a.5.5 0 0 1 .708 0l2.5 2.5a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12h.5a.5.5 0 0 1 .5.5v.5a.5.5 0 0 1-.5.5h-.5a.5.5 0 0 1-.468-.325z"/>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="12" cy="12" r="10"></circle>`,`<polyline points="12 6 12 12 16 14"></polyline>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<line x1="18" y1="6" x2="6" y2="18"></line>`,`<line x1="6" y1="6" x2="18" y2="18"></line>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="7 13 12 18 17 13"></polyline>`,`<polyline points="7 6 12 11 17 6"></polyline>`,`</svg>`].join(``);var oc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`,sc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`,cc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>`,lc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,uc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,dc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>`;[`<svg class="tool-call-icon exec" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>`,`<polyline points="14 2 14 8 20 8"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>`,`</svg>`].join(``),n(`zh`,{uiProto:{defaultTitle:`原型`,optimizePrompt:`请帮我优化这个UI原型界面 {id}({title}),`,loadFailed:`加载失败`,noDescription:`暂无描述`,previewInPanel:`面板内预览`,continueOptimizeTitle:`继续优化`,downloadPrototype:`下载原型`,confirmDeleteTitle:`确认删除`,confirmDeleteMessage:`确定删除原型 "{title}" 吗?此操作不可撤销。`,deleteFailed:`删除失败: {message}`,justNow:`刚刚`,minutesAgo:`{count} 分钟前`,hoursAgo:`{count} 小时前`}}),n(`en`,{uiProto:{defaultTitle:`Prototype`,optimizePrompt:`Please help me optimize this UI prototype {id} ({title}), `,loadFailed:`Load failed`,noDescription:`No description`,previewInPanel:`Preview in panel`,continueOptimizeTitle:`Continue optimizing`,downloadPrototype:`Download prototype`,confirmDeleteTitle:`Confirm delete`,confirmDeleteMessage:`Are you sure you want to delete prototype "{title}"? This action cannot be undone.`,deleteFailed:`Delete failed: {message}`,justNow:`Just now`,minutesAgo:`{count} minutes ago`,hoursAgo:`{count} hours ago`}});var fc=null,pc=1,mc=.25,hc=2,gc=.1;function _c(e){let t=e.trim();return/^\s*<!DOCTYPE\s/i.test(t)||/^\s*<html[\s>]/i.test(t)?/<\/head>/i.test(t)?t.replace(/<\/head>/i,`<style>html,body{overflow:auto!important;height:auto!important;}</style></head>`):/<body[\s>]/i.test(t)?t.replace(/<body([\s>])/i,`<body$1<style>html,body{overflow:auto!important;height:auto!important;}</style>`):t:`<!DOCTYPE html>
|
|
61
61
|
<html>
|
|
62
62
|
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
|
|
63
63
|
<body style="margin:0;padding:0;overflow:auto;">${t}</body>
|
|
@@ -91,17 +91,17 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
91
91
|
</button>
|
|
92
92
|
</div>
|
|
93
93
|
</div>
|
|
94
|
-
`}).join(``),t.querySelectorAll(`.prototype-library-item`).forEach(e=>{let t=e.querySelector(`.prototype-library-item-info`),n=e.querySelector(`.prototype-library-item-open`),a=e.querySelector(`.prototype-library-item-local-open`),o=e.querySelector(`.prototype-library-item-optimize`),s=e.querySelector(`.prototype-library-item-delete`),c=e.querySelector(`.prototype-library-item-download`);t&&t.addEventListener(`click`,()=>{let t=e.dataset.id;Cc(t)}),n&&n.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.id;Cc(n)}),a&&a.addEventListener(`click`,e=>{e.stopPropagation();let t=a.dataset.path;chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:t},e=>{e?.success||i.error(`[SidePanel] local browseropen failed:`,e?.error)})}),o&&o.addEventListener(`click`,t=>{t.stopPropagation();let n=o.dataset.id;kc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`)),Oc()}),s&&s.addEventListener(`click`,t=>{t.stopPropagation();let n=s.dataset.id;jc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`))}),c&&c.addEventListener(`click`,e=>{e.stopPropagation();let t=c.dataset.id;Ac(t)})})))}function Dc(e){let t=()=>{let t=document.getElementById(`prototypeLibrarySearch`),n=document.getElementById(`prototypeLibrarySort`),r=(t?.value||``).trim().toLowerCase(),i=n?.value||`createdAt_desc`,a=e;r&&(a=e.filter(e=>(e.title||``).toLowerCase().includes(r)||(e.description||``).toLowerCase().includes(r)));let[o,s]=i.split(`_`);a=[...a].sort((e,t)=>{let n;return n=o===`title`?(e.title||``).localeCompare(t.title||``,`zh-CN`):(e.createdAt||0)-(t.createdAt||0),s===`desc`?-n:n}),Ec(a)},n=document.getElementById(`prototypeLibrarySearch`),r=document.getElementById(`prototypeLibrarySort`);if(n){let e=n.cloneNode(!0);n.parentNode.replaceChild(e,n),e.addEventListener(`input`,t)}if(r){let e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener(`change`,t)}}function Oc(){let e=document.getElementById(`prototypeLibraryModal`);e&&e.classList.remove(`show`),i.debug(`[SidePanel] prototype page libraryhidden`)}function kc(e,t){let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),i.debug(`[SidePanel] from prototype page librarycontinue optimizeprototype:`,e)}async function Ac(e){try{let t=await D(e);if(!t||!t.html){i.error(`[SidePanel] download prototype failed:not foundprototype`,e);return}let n=_c(t.html),r=new Blob([n],{type:`text/html`}),a=URL.createObjectURL(r),o=document.createElement(`a`);o.href=a,o.download=(t.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a),i.debug(`[SidePanel] prototype fromprototypelibrarydownload:`,o.download)}catch(e){i.error(`[SidePanel] download prototype failed:`,e)}}async function jc(e,t){if(await Mc(r(`uiProto.confirmDeleteTitle`),r(`uiProto.confirmDeleteMessage`,{title:t}),r(`common.delete`)))try{let t=await D(e);await x(e),i.debug(`[SidePanel] prototype deleted:`,e),t?.localPath&&chrome.runtime.sendMessage({type:`DELETE_LOCAL_PROTOTYPE`,path:t.localPath},e=>{e?.success?i.debug(`[SidePanel] local prototypefile deleted:`,t.localPath):i.warn(`[SidePanel] local prototypefiledelete failed:`,e?.error)}),Tc()}catch(e){i.error(`[SidePanel] delete prototype failed:`,e),alert(r(`uiProto.deleteFailed`,{message:e.message}))}}function Mc(e,t,n=r(`common.confirm`)){return new Promise(r=>{let i=document.getElementById(`genericConfirmModal`),a=document.getElementById(`genericConfirmTitle`),o=document.getElementById(`genericConfirmMessage`),s=document.getElementById(`genericConfirmOkBtn`),c=document.getElementById(`genericConfirmCancelBtn`);if(!i){r(confirm(t));return}a.textContent=e,o.textContent=t,s.textContent=n;let l=()=>{i.classList.remove(`show`),s.removeEventListener(`click`,u),c.removeEventListener(`click`,d)},u=()=>{l(),r(!0)},d=()=>{l(),r(!1)};s.addEventListener(`click`,u),c.addEventListener(`click`,d),i.classList.add(`show`)})}function Nc(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function Pc(e){if(!e)return``;let t=new Date(e),n=new Date-t;return n<6e4?r(`uiProto.justNow`):n<36e5?r(`uiProto.minutesAgo`,{count:Math.floor(n/6e4)}):n<864e5?r(`uiProto.hoursAgo`,{count:Math.floor(n/36e5)}):t.toLocaleDateString(`zh-CN`)}function Fc(e){pc=Math.max(mc,Math.min(hc,e)),pc=Math.round(pc*100)/100;let t=document.getElementById(`prototypeIframe`),n=document.getElementById(`prototypeZoomLevel`);t&&(t.style.zoom=pc),n&&(n.textContent=Math.round(pc*100)+`%`,pc===1?n.classList.remove(`zoomed`):n.classList.add(`zoomed`))}function Ic(){Fc(pc+gc),zc()}function Lc(){Fc(pc-gc),zc()}function Rc(){Fc(1)}function zc(){let e=document.getElementById(`prototypeZoomLevel`);e&&(e.classList.add(`flash`),setTimeout(()=>e.classList.remove(`flash`),150))}function Bc(e){!e.ctrlKey&&!e.metaKey||(e.preventDefault(),e.deltaY<0?Ic():Lc())}function Vc(e){(e.ctrlKey||e.metaKey)&&e.key===`0`&&(e.preventDefault(),Rc())}function Hc(){let e=document.getElementById(`prototypeCloseBtn`);e&&e.addEventListener(`click`,yc);let t=document.getElementById(`prototypeDownloadBtn`);t&&t.addEventListener(`click`,xc);let n=document.getElementById(`prototypeOpenTabBtn`);n&&n.addEventListener(`click`,Sc);let r=document.getElementById(`prototypeLocalOpenBtn`);r&&r.addEventListener(`click`,()=>{let e=r.dataset.path;e&&chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:e},e=>{e?.success||i.error(`[SidePanel] local browseropen failed:`,e?.error)})});let a=document.getElementById(`prototypeContinueBtn`);a&&a.addEventListener(`click`,bc);let o=document.getElementById(`prototypeZoomInBtn`);o&&o.addEventListener(`click`,Ic);let s=document.getElementById(`prototypeZoomOutBtn`);s&&s.addEventListener(`click`,Lc);let c=document.getElementById(`prototypeZoomLevel`);c&&c.addEventListener(`click`,Rc);let l=document.getElementById(`prototypeContent`);l&&l.addEventListener(`wheel`,Bc,{passive:!1}),document.addEventListener(`keydown`,Vc);let u=document.getElementById(`prototypeLibraryCloseBtn`);u&&u.addEventListener(`click`,Oc),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_UI_PROTOTYPE`&&(i.debug(`[SidePanel] received showprototyperequested :`,e),e.data.localOpened?i.debug(`[SidePanel] prototype inagent-side browseropen,skip popup`):e.data.isRemoteAgent?(i.debug(`[SidePanel] remoteagent,will use browserlabelpageautoopenprototype`),wc(e.data.prototypeId)):Cc(e.data.prototypeId),n({success:!0}))}),i.debug(`[SidePanel] UI prototype moduleeventinitializing`)}var Uc={enabled:!1,thresholdRatio:.85,minPending:4,maxFailures:2};function Wc(e,t){let n=Number(e);return Number.isFinite(n)&&n>0&&n<=1?n:t}function Gc(e,t){let n=Number(e);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function Kc({enabled:e,ratio:t,thresholdRatio:n,pendingCount:r,minPending:i,isGenerating:a,isolateChat:o}={}){if(!e||a||!o)return!1;let s=Wc(n,Uc.thresholdRatio),c=Gc(i,Uc.minPending);return!Number.isFinite(t)||t<s?!1:Gc(r,0)>=c}function qc(e){let t=e?.messageHistory||[],n=e?.activeCompaction?.upToMessageId;if(!n)return t.length;let r=t.findIndex(e=>e.messageId===n);return r===-1?t.length:t.length-r-1}var Jc=0;function Yc(){Jc=0}async function Xc({state:e,getRatio:t,compact:n}={}){let r=e?.chatConfig||{},a=r.autoCompaction===!0;if(!a)return{attempted:!1,success:!1,reason:`disabled`};if(Jc>=Uc.maxFailures)return{attempted:!1,success:!1,reason:`backoff`};let o;try{o=Number(t?t():NaN)}catch(e){return i.warn(`[AutoCompaction] usage compute failed, send continues:`,e?.message),{attempted:!1,success:!1,reason:`usage_unavailable`}}let s=qc(e);if(!Kc({enabled:a,ratio:o,thresholdRatio:r.autoCompactionThreshold,pendingCount:s,isGenerating:!!e?.isGenerating,isolateChat:!!e?.isolateChat}))return{attempted:!1,success:!1,reason:`not_needed`};i.debug(`[AutoCompaction] triggered`,{ratio:o,pendingCount:s});let c=null;try{c=await n({silent:!0})}catch(e){return i.warn(`[AutoCompaction] compact threw, send continues:`,e?.message),Jc++,{attempted:!0,success:!1,reason:`exception`}}return c?.success?(Yc(),{attempted:!0,success:!0}):(Jc++,i.debug(`[AutoCompaction] skipped send:`,c?.reason),{attempted:!0,success:!1,reason:c?.reason||`failed`})}var Zc=null,Qc=`global`,$c=new Map;function el(){try{chrome.windows?.getCurrent?.().then?.(e=>{e?.id!=null&&(Zc=e.id)}).catch?.(e=>{i.debug(`[PanelContext] query current window failed:`,e?.message)})}catch(e){i.debug(`[PanelContext] init window query failed:`,e?.message)}try{chrome.storage?.local?.get?.([`sidePanelScope`],e=>{Qc=e?.sidePanelScope===`tab-specific`?`tab-specific`:`global`}),chrome.storage?.onChanged?.addListener?.((e,t)=>{t!==`local`||!e?.sidePanelScope||(Qc=e.sidePanelScope.newValue===`tab-specific`?`tab-specific`:`global`)})}catch(e){i.debug(`[PanelContext] init scope mirror failed:`,e?.message)}}function tl(){return Zc}function nl(e){e&&typeof C.currentTabId==`number`&&$c.set(e,C.currentTabId)}function rl(e,t){e&&(typeof t==`number`?$c.set(e,t):$c.delete(e))}function il(e){if(!e)return null;let t=$c.get(e);return typeof t==`number`?t:null}function al(e){let t=null;try{t=typeof document<`u`?!!document.hidden:null}catch{}return{windowId:Zc,hostTabId:il(e),scope:Qc,panelHidden:t}}var ol=0,sl=500,cl=[{frequency:523.25,startTime:0,duration:.12,type:`sine`,gain:.3},{frequency:659.25,startTime:.09,duration:.12,type:`sine`,gain:.3},{frequency:783.99,startTime:.18,duration:.22,type:`sine`,gain:.35}],ll=[{frequency:440,startTime:0,duration:.16,type:`square`,gain:.22},{frequency:349.23,startTime:.14,duration:.3,type:`square`,gain:.22}],ul=[`#FF3B30`,`#FF9500`,`#FFCC00`,`#34C759`,`#00C7BE`,`#007AFF`,`#AF52DE`,`#FF2D55`],dl=120,fl=4e3,pl=600,ml=1e3,hl=.25,gl=.99,_l=.3,vl=.6,yl=9999;function bl(){return new Promise(e=>{try{chrome.storage.local.get([`completionSoundEnabled`,`completionConfettiEnabled`],t=>{e({soundEnabled:t?.completionSoundEnabled!==!1,confettiEnabled:t?.completionConfettiEnabled!==!1})})}catch(t){i.debug(`[CompletionFeedback] read config failed, use defaults:`,t?.message),e({soundEnabled:!0,confettiEnabled:!0})}})}function xl(e){try{let t=window.AudioContext||window.webkitAudioContext;if(!t){i.debug(`[CompletionFeedback] AudioContext unavailable`);return}let n=new t;n.state===`suspended`&&typeof n.resume==`function`&&n.resume().catch(()=>{});let r=n.currentTime,a=0;for(let t of e){let e=n.createOscillator(),i=n.createGain();e.type=t.type||`sine`,e.frequency.value=t.frequency;let o=r+t.startTime,s=o+t.duration;i.gain.setValueAtTime(1e-4,o),i.gain.exponentialRampToValueAtTime(t.gain,o+.012),i.gain.exponentialRampToValueAtTime(1e-4,s),e.connect(i),i.connect(n.destination),e.start(o),e.stop(s+.02),s>a&&(a=s)}let o=Math.max(0,(a-r)*1e3)+200;setTimeout(()=>{try{n.close()}catch{}},o)}catch(e){i.debug(`[CompletionFeedback] play tone failed:`,e?.message)}}function Sl(){xl(cl),i.debug(`[CompletionFeedback] success sound played`)}function Cl(){xl(ll),i.debug(`[CompletionFeedback] failure sound played`)}function wl(){try{return typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{return!1}}function Tl(){try{if(!document.body)return;let e=window.innerWidth,t=window.innerHeight;if(e<=0||t<=0)return;let n=document.createElement(`canvas`);n.style.cssText=`position:fixed;inset:0;pointer-events:none;z-index:${yl};`;let r=window.devicePixelRatio||1;n.width=Math.floor(e*r),n.height=Math.floor(t*r),n.style.width=e+`px`,n.style.height=t+`px`,document.body.appendChild(n);let a=n.getContext(`2d`);if(!a){n.remove();return}a.scale(r,r);let o=[{x:e*.15,y:t+10,baseAngle:-Math.PI/2+_l},{x:e*.85,y:t+10,baseAngle:-Math.PI/2-_l}],s=[],c=0,l=0,u=performance.now(),d=e=>{let t=Math.min(dl,Math.floor(Math.min(e,pl)/pl*dl));for(;c<t;){let e=o[c%o.length],t=e.baseAngle+(Math.random()-.5)*vl,n=12+Math.random()*8,r=4+Math.random()*4;s.push({x:e.x+(Math.random()-.5)*20,y:e.y,vx:Math.cos(t)*n,vy:Math.sin(t)*n,size:r,color:ul[Math.floor(Math.random()*ul.length)],rotation:Math.random()*Math.PI*2,rotationSpeed:(Math.random()-.5)*.3,shape:Math.random()<.5?`rect`:`circle`}),c++}},f=r=>{let i=r-u;if(i>=fl){cancelAnimationFrame(l),n.remove();return}d(i),a.clearRect(0,0,e,t);let o=fl-ml,c=i>o?Math.max(0,1-(i-o)/ml):1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.vy+=hl,r.vx*=gl,r.vy*=gl,r.x+=r.vx,r.y+=r.vy,r.rotation+=r.rotationSpeed,r.y-r.size>t||r.x+r.size<0||r.x-r.size>e){s.splice(n,1);continue}a.save(),a.globalAlpha=c,a.translate(r.x,r.y),a.rotate(r.rotation),a.fillStyle=r.color,r.shape===`rect`?a.fillRect(-r.size/2,-r.size/2,r.size,r.size*.6):(a.beginPath(),a.arc(0,0,r.size/2,0,Math.PI*2),a.fill()),a.restore()}l=requestAnimationFrame(f)};l=requestAnimationFrame(f),i.debug(`[CompletionFeedback] confetti launched`)}catch(e){i.debug(`[CompletionFeedback] launch confetti failed:`,e?.message)}}function El(e,t,n,r){try{chrome.runtime.sendMessage({type:`TASK_FEEDBACK_NOTIFY`,success:e,sessionId:t||null,error:n||``,question:r||``,panel:al(t)})?.catch?.(()=>{})}catch(e){i.debug(`[CompletionFeedback] desktop notify failed:`,e?.message)}}async function Dl(e=null,t=``){try{let n=Date.now();if(n-ol<sl){i.debug(`[CompletionFeedback] throttled, skip`);return}ol=n;let{soundEnabled:r,confettiEnabled:a}=await bl();r&&Sl(),a&&!wl()&&Tl(),El(!0,e,``,t)}catch(e){i.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}async function Ol(e=null,t=``,n=``){try{let r=Date.now();if(r-ol<sl){i.debug(`[CompletionFeedback] throttled, skip`);return}ol=r;let{soundEnabled:a}=await bl();a&&Cl(),El(!1,e,t,n)}catch(e){i.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}var kl=new Set;function Al(e){return typeof e==`function`?(kl.add(e),()=>kl.delete(e)):()=>{}}function jl(e){let t=e||C.activeSessionId;if(t){C.generatingSessionIds.delete(t);try{$r(t)}catch(e){i.warn(`[GenerationLifecycle] markSessionCompleted failed:`,e?.message)}typeof document<`u`&&typeof CustomEvent==`function`&&(document.dispatchEvent(new CustomEvent(`generating-state-changed`)),document.dispatchEvent(new CustomEvent(`generation-ended`,{detail:{sessionId:t}})));for(let e of kl)try{e(t)}catch(e){i.error(`[GenerationLifecycle] end handler failed:`,e?.message)}}}function Ml(e){let t=Number(e);return!Number.isFinite(t)||t<=0?3:Math.min(20,Math.max(1,Math.round(t)))}function Nl(){return{callId:null,carried:0,lastIteration:null}}function Pl(e){let t=0;for(let n of e||[]){let e=Number(n&&n.iteration);Number.isFinite(e)&&e>t&&(t=e)}return t}function Fl(e){let{tracker:t,callId:n=null,iteration:r,everyN:i,enabled:a=!0,hasCandidate:o=!0}=e||{},s=t&&typeof t==`object`?{callId:t.callId??null,carried:Number(t.carried)||0,lastIteration:t.lastIteration??null}:Nl(),c=Number(r);if(!Number.isFinite(c)||c<=0)return{carry:!1,reason:`invalid_iteration`,tracker:s};let l=!!n&&!!s.callId&&n!==s.callId,u=s.lastIteration!=null&&c<s.lastIteration;if((l||u)&&(s=Nl()),n&&!s.callId&&(s={...s,callId:n}),!a)return{carry:!1,reason:`disabled`,tracker:s};if(c<2)return{carry:!1,reason:`too_early`,tracker:s};if(!o)return{carry:!1,reason:`no_candidate`,tracker:s};if(s.carried>=3)return{carry:!1,reason:`call_limit`,tracker:s};let d=Ml(i);return s.lastIteration!=null&&c-s.lastIteration<d?{carry:!1,reason:`interval_not_reached`,tracker:s}:{carry:!0,reason:`carry`,tracker:{callId:s.callId||n||null,carried:s.carried,lastIteration:c}}}function Il(e,{callId:t=null}={}){let n=e&&typeof e==`object`?e:Nl();return t&&n.callId&&t!==n.callId?n:{...n,carried:(Number(n.carried)||0)+1}}var Ll=/[\p{P}\p{S}]/gu;function Rl(e){return Array.isArray(e)?e.map(e=>e&&e.text||``).join(``):``}function zl(e){return String(e||``).replace(/[\s\u3000]/g,``).replace(Ll,``)}function Bl(e,t){if(!Array.isArray(e))return e;let n=t&&t.id,r=t&&typeof t.text==`string`?t.text:null;if(r===null||typeof n!=`number`)return e;let i=!1,a=e.map(e=>!e||e.id!==n||e.state===`locked`?e:(i=!0,{...e,text:r}));return i?a:e}function Vl(e,t,n){let r=String(t||``),i=String(n||``),a={lockedIds:[],shift:0,items:e,len:r.length};if(r===i||!Array.isArray(e)||e.length===0)return a;let o=0,s=Math.min(r.length,i.length);for(;o<s&&r[o]===i[o];)o++;let c=0,l=Math.min(r.length-o,i.length-o);for(;c<l&&r[r.length-1-c]===i[i.length-1-c];)c++;let u=o,d=r.length-c;if(u>=r.length&&d>=r.length){let t=e[e.length-1],n=t&&t.text?t.text.length:0,a=i.slice(Math.max(0,r.length-n)),o=e.map((t,n)=>n===e.length-1?{...t,text:a}:t);return{lockedIds:[t.id],shift:0,items:o,len:i.length}}let f=[],p=0;for(let t of e){let e=(t&&t.text?t.text:``).length;u<p+e&&d>p&&f.push(t.id),p+=e}if(f.length===0)return{lockedIds:[],shift:u===0?i.length-r.length:0,items:e,len:r.length};let m=i.length-r.length,h=d+m,g=e=>e<=u?e:e>=d?e+m:u+Math.min(e-u,Math.max(0,h-u)),_=0;return{lockedIds:f,shift:0,items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=g(_),r=g(_+t);return _+=t,{...e,text:i.slice(n,r)}}),len:i.length}}function Hl(e,t){if(!Array.isArray(e)||e.length===0)return{items:Array.isArray(e)?e:[],changed:0,takeAll:!1};let n=Rl(e),r=String(t||``);if(!r)return{items:e,changed:0,takeAll:!1};let i=zl(n),a=zl(r);if(i===a)return{items:e,changed:0,takeAll:!1};if(Math.abs(i.length-a.length)+Ul(i,a)>2||i.length!==a.length)return e.some(e=>e&&e.state===`locked`)?{items:e,changed:0,takeAll:!1}:{items:[{id:e[0]&&typeof e[0].id==`number`?e[0].id:null,text:r,state:`refined`}],changed:1,takeAll:!0};let o=n.split(``),s=0,c=0;for(let e=0;e<o.length;e++)zl(o[e])!==``&&(s<a.length&&o[e]!==a[s]&&(o[e]=a[s],c+=1),s+=1);if(c===0)return{items:e,changed:0,takeAll:!1};let l=o.join(``),u=0;return{items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=e&&e.state===`locked`?e.text:l.slice(u,u+t);return u+=t,e&&e.state===`locked`?e:{...e,text:n}}),changed:c,takeAll:!1}}function Ul(e,t){if(e.length!==t.length)return 2**53-1;let n=0;for(let r=0;r<e.length;r++)e[r]!==t[r]&&(n+=1);return n}n(`zh`,{voice:{start:`语音输入(开始录音)`,stop:`结束录音并转写`,recording:`正在录音`,listening:`正在聆听…`,transcribing:`正在转写…`,cancel:`取消录音`,done:`完成`,noSpeech:`没有听到声音`,noResult:`未识别到语音`,micDenied:`麦克风未授权`,micDeniedHelp:`侧边栏里浏览器不会弹授权框,请到配置页「语音输入 → 麦克风权限」授权一次`,micDeniedAction:`去授权`,micDeniedActionTitle:`打开配置页授权麦克风(侧边栏内无法弹出授权框)`,unavailable:`语音功能不可用`,modelMissing:`缺少语音模型`,modelMissingHelp:`请在配置页「语音」Tab 中导入模型包`,busy:`有语音任务正在进行`,failed:`语音识别失败`,connectionLost:`连接中断`,tooShort:`录音太短`,maxDuration:`已达单次录音时长上限,正在转写…`,unsupported:`当前浏览器不支持录音`,keyRightAlt:`右侧 Alt`,keyRightCtrl:`右侧 Ctrl`,btnTitle:`语音输入({keys})`,deviceFallback:`原麦克风不可用,已改用系统默认`,refineListening:`正在听…(已定稿 {n} 句)`,refineCorrecting:`正在校正…`,refineCorrected:`已校正 {n} 处`,refineDegraded:`本机性能有限,已关闭逐句精修(松手后仍会整体校正)`}}),n(`en`,{voice:{start:`Voice input (start recording)`,stop:`Stop and transcribe`,recording:`Recording`,listening:`Listening…`,transcribing:`Transcribing…`,cancel:`Cancel recording`,done:`Done`,noSpeech:`No sound detected`,noResult:`No speech recognised`,micDenied:`Microphone not granted`,micDeniedHelp:`The browser cannot prompt inside the side panel — grant it once in Options → Voice Input → Microphone permission`,micDeniedAction:`Grant access`,micDeniedActionTitle:`Open options to grant microphone access (the side panel cannot show the prompt)`,unavailable:`Voice input unavailable`,modelMissing:`Speech model missing`,modelMissingHelp:`Import a model pack in the Options "Voice" tab`,busy:`Another voice task is running`,failed:`Speech recognition failed`,connectionLost:`Connection lost`,tooShort:`Recording too short`,maxDuration:`Recording length limit reached, transcribing…`,unsupported:`Recording is not supported in this browser`,keyRightAlt:`Right Alt`,keyRightCtrl:`Right Ctrl`,btnTitle:`Voice input ({keys})`,deviceFallback:`Selected microphone unavailable — using the system default`,refineListening:`Listening… ({n} sentences finalized)`,refineCorrecting:`Refining…`,refineCorrected:`{n} correction(s) applied`,refineDegraded:`This machine is too slow for per-sentence refinement (the final pass still runs)`}});var Wl=15e3,Gl=16e3,Kl=2500,ql=.008,Jl=350,Yl=24,H={input:null,btn:null,bar:null,wave:null,timerEl:null,statusEl:null,permBtn:null,barEls:[],status:null,armed:!1,phase:`idle`,port:null,stream:null,ctx:null,node:null,source:null,startedAt:0,timer:null,silentSince:0,silenceWarned:!1,draft:null,lastText:``,appliedText:``,appliedValue:``,openText:``,mute:null,programmatic:!1,draftSupported:!0,finishWaitTimer:null,adjustInputHeight:null,shortcutCfg:{...Ae},shortcutTrigger:null,shortcutBound:!1,deviceFellBack:!1};function Xl(e){return typeof e==`string`?e:``}function Zl(e){let t=Math.max(0,Math.floor(e/1e3));return`${String(Math.floor(t/60)).padStart(2,`0`)}:${String(t%60).padStart(2,`0`)}`}function Ql(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode.apply(null,t.subarray(e,e+r));return btoa(n)}function $l(e,t,n){if(t===n)return e;let r=t/n,i=Math.floor(e.length/r),a=new Float32Array(i);for(let t=0;t<i;t++){let n=t*r,i=Math.floor(n),o=n-i,s=e[i]||0;a[t]=s+((e[i+1]===void 0?s:e[i+1])-s)*o}return a}function eu(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++){let r=e[n]<-1?-1:e[n]>1?1:e[n];t[n]=r<0?r*32768:r*32767}return t}async function tu(e=!1){try{let t=await chrome.runtime.sendMessage({type:`ASR_GET_STATUS`,force:e});if(t&&t.success&&t.status)return H.status=t.status,H.status}catch(e){i.debug(`[Voice] status fetch failed:`,e?.message||e)}return H.status=null,null}function nu(e){return!e||e.success===!1?!1:typeof e.available==`boolean`?e.available:e.deps?.ready===!0&&e.modelsReady===!0&&e.enabled===!0}function ru({value:e,draft:t,text:n,caret:r,canReplace:i=!0}){let a=typeof e==`string`?e:``;if(!t)return{value:a,caret:a.length,len:0};if(!i){let e=typeof r==`number`?Math.min(Math.max(0,r),a.length):a.length;return{value:a.slice(0,e)+n+a.slice(e),caret:e+n.length,len:0}}let o=Math.min(Math.max(0,t.start),a.length),s=Math.min(Math.max(o,t.start+t.len),a.length);return{value:a.slice(0,o)+n+a.slice(s),caret:o+n.length,len:n.length}}function iu({value:e,draft:t,canReplace:n=!0}){let r=typeof e==`string`?e:``;if(!t||!n||t.len<=0)return{value:r,caret:r.length};let i=Math.min(Math.max(0,t.start),r.length),a=Math.min(Math.max(i,t.start+t.len),r.length);return{value:r.slice(0,i)+r.slice(a),caret:i}}function au(e){return!e||e.isComposing||e.repeat?!1:e.altKey===!0&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyV`}async function ou(){return H.armed=nu(await tu()),H.btn&&(H.btn.style.display=H.armed?``:`none`),!H.armed&&H.phase!==`idle`&&Lu({rollback:!0}),H.armed}function su(){if(!H.draft||!H.input)return;let e=Rl(H.draft.items),t=H.input.value,n=Xl(H.appliedValue),r=H.draft.start,i=r+e.length,a=0;for(;a<n.length&&a<t.length&&n[a]===t[a];)a+=1;let o=0,s=Math.min(n.length-a,t.length-a);for(;o<s&&n[n.length-1-o]===t[t.length-1-o];)o+=1;let c=a;if(n.length-o<=r){H.draft.start=Math.max(0,r+(t.length-n.length));return}if(c>i)return;let l=Math.max(0,n.length-i),u=t.slice(r,Math.max(r,t.length-l)),d=Vl(H.draft.items,e,u);d.shift&&(H.draft.start+=d.shift),d.lockedIds.length!==0&&(H.draft.items=d.items.map(e=>d.lockedIds.includes(e.id)?{...e,state:`locked`}:e),H.draft.len=d.len)}function cu(){let e=H.input;if(!e)return{start:0,len:0,items:[]};let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length,n=typeof e.selectionEnd==`number`?e.selectionEnd:t;return t!==n&&e.setRangeText(``,t,n,`end`),{start:t,len:0,items:[]}}function lu(e,t){let n=Xl(e),r=Xl(t);return r?n?r.startsWith(n)?r.slice(n.length):null:r:``}function uu(e,t){let n=H.input;if(n){H.programmatic=!0,H.appliedValue=e,n.value=e;try{n.setSelectionRange(t,t)}catch{}H.programmatic=!1;try{document.dispatchEvent(new CustomEvent(`voice-draft-written`))}catch{}try{H.adjustInputHeight?.()}catch{}try{n.focus()}catch{}}}function du(e=!1){let t=H.input;if(!t||!H.draft)return;let n=Rl(H.draft.items);if(!e&&n===Xl(H.appliedText))return;let r=typeof t.selectionStart==`number`?t.selectionStart:void 0,i=H.draft.start,a=i+H.draft.len,o=ru({value:t.value,draft:{start:i,len:H.draft.len},text:n,caret:r,canReplace:H.draftSupported});typeof r==`number`&&r>i&&r<a&&(o.caret=i+Math.min(r-i,n.length)),H.draft.len=n.length,H.appliedText=n,uu(o.value,o.caret)}function fu(e){if(!H.input||!H.draft)return;let t=Array.isArray(H.draft.items)?H.draft.items:[],n=t.findIndex(e=>e.id===null),r=Xl(e);if(n>=0&&t[n].state===`locked`){let e=lu(H.openText,r);if(H.openText=r,!e)return;H.draft.items=t.map((t,r)=>r===n?{...t,text:t.text+e}:t)}else H.openText=r,H.draft.items=n>=0?t.map((e,t)=>t===n?{...e,text:r}:e):t.concat([{id:null,text:r,state:`draft`}]);du()}function pu(){let e=H.input;if(!e||!H.draft)return;let t=Array.isArray(H.draft.items)&&H.draft.items.some(e=>e.state===`locked`)?{value:e.value,caret:e.value.length}:iu({value:e.value,draft:H.draft,canReplace:H.draftSupported});if(t.value!==e.value){H.programmatic=!0,H.appliedValue=t.value,e.value=t.value;let n=Math.min(t.caret,e.value.length);try{e.setSelectionRange(n,n)}catch{}H.programmatic=!1;try{H.adjustInputHeight?.()}catch{}}H.draft=null,H.lastText=``,H.appliedText=``,H.openText=``}function mu(){if(H.wave){H.wave.textContent=``,H.barEls=[];for(let e=0;e<Yl;e++){let e=document.createElement(`i`);H.wave.appendChild(e),H.barEls.push(e)}}}function hu(e,t=``){H.statusEl&&(H.statusEl.textContent=e,H.statusEl.className=`voice-recorder-status`+(t?` is-${t}`:``))}function gu(){H.bar&&(H.bar.classList.add(`show`),H.bar.removeAttribute(`aria-hidden`))}function _u(e){H.permBtn&&(H.permBtn.style.display=e?``:`none`)}function vu(){let e=document.activeElement;if(!(!H.bar||!e||!H.bar.contains(e))){if(H.input&&typeof H.input.focus==`function`)try{H.input.focus({preventScroll:!0});return}catch{}try{e.blur()}catch{}}}function yu(){H.bar&&(typeof document>`u`||!document.body||(vu(),_u(!1),H.bar.classList.remove(`show`),H.bar.setAttribute(`aria-hidden`,`true`),H.barEls.forEach(e=>{e.style.height=``,e.style.opacity=``}),H.timerEl&&(H.timerEl.textContent=`00:00`)))}function bu(e){if(!H.barEls.length)return;let t=Math.min(1,Math.sqrt(Math.max(0,e))*6);for(let e=0;e<H.barEls.length-1;e++)H.barEls[e].style.height=H.barEls[e+1].style.height,H.barEls[e].style.opacity=H.barEls[e+1].style.opacity;let n=H.barEls[H.barEls.length-1];n.style.height=`${Math.max(2,Math.round(t*18))}px`,n.style.opacity=t>.06?`1`:`0.35`}function xu(e){H.btn&&(H.btn.classList.toggle(`recording`,e),H.btn.setAttribute(`aria-pressed`,e?`true`:`false`),H.btn.setAttribute(`aria-label`,r(e?`voice.stop`:`voice.start`)),H.btn.title=r(e?`voice.stop`:`voice.start`))}function Su(e){document.body?.classList.toggle(`voice-recording-active`,!!e)}function Cu(){if(H.port)return H.port;try{let e=chrome.runtime.connect({name:`asr`});return e.onMessage.addListener(zu),e.onDisconnect.addListener(()=>{H.port=null,(H.phase===`recording`||H.phase===`finalizing`)&&(Mu(),Nu(),H.draft=null,H.lastText=``,xu(!1),Su(!1),hu(r(`voice.connectionLost`),`warn`),setTimeout(()=>{H.phase===`idle`&&yu()},3500))}),H.port=e,e}catch(e){return i.warn(`[Voice] connect port failed:`,e?.message||e),null}}function wu(e,t){if(bu(t),Tu(t),H.port)try{H.port.postMessage({type:`audio`,data:Ql(e)})}catch(e){i.debug(`[Voice] post audio failed:`,e?.message||e)}}function Tu(e){if(H.phase!==`recording`&&H.phase!==`starting`)return;if(e>=ql){H.silentSince=0,H.silenceWarned&&(H.silenceWarned=!1,hu(r(`voice.listening`)));return}let t=Date.now();if(!H.silentSince){H.silentSince=t;return}H.silenceWarned||t-H.silentSince>=Kl&&(H.silenceWarned=!0,hu(r(`voice.noSpeech`),`warn`))}var Eu=[`voice-capture-worklet.js`,`dist/voice-capture-worklet.js`],Du;async function Ou(){if(Du!==void 0)return Du;for(let e of Eu){let t=``;try{t=chrome.runtime.getURL(e)}catch{continue}try{let e=await fetch(t);if(e&&e.ok)return Du=t,t}catch{}}return Du=null,null}async function ku(e,t){let n=await Ou();if(!n)throw Error(`worklet not found in extension`);await e.audioWorklet.addModule(n);let r=new AudioWorkletNode(e,`voice-capture`),i=Math.abs(e.sampleRate-Gl)>1;r.port.onmessage=t=>{let n=t.data;if(!n||n.type!==`chunk`||!n.pcm)return;let r=new Int16Array(n.pcm);if(i){let t=new Float32Array(r.length);for(let e=0;e<r.length;e++)t[e]=r[e]/32768;r=eu($l(t,e.sampleRate,Gl))}wu(r,n.rms||0)},t.connect(r),H.node=r}function Au(e,t){let n=e.createScriptProcessor(4096,1,1),r=Math.abs(e.sampleRate-Gl)>1;n.onaudioprocess=t=>{let n=t.inputBuffer.getChannelData(0),i=new Float32Array(n);r&&(i=$l(i,e.sampleRate,Gl));let a=0;for(let e=0;e<i.length;e++)a+=i[e]*i[e];wu(eu(i),Math.sqrt(a/Math.max(1,i.length)))},t.connect(n);let i=e.createGain();i.gain.value=0,n.connect(i),i.connect(e.destination),H.mute=i,H.node=n}async function ju(){if(!navigator.mediaDevices?.getUserMedia)throw hu(r(`voice.unsupported`),`warn`),Error(`unsupported`);let e=await ot(await tt());H.stream=e.stream,H.deviceFellBack=e.fellBack===!0;let t=window.AudioContext||window.webkitAudioContext,n;try{n=new t({sampleRate:Gl})}catch{n=new t}if(n.state===`suspended`)try{await n.resume()}catch{}H.ctx=n;let a=n.createMediaStreamSource(e.stream);H.source=a;try{await ku(n,a)}catch(e){i.warn(`[Voice] worklet unavailable, fallback to ScriptProcessor:`,e?.message||e),Au(n,a)}}function Mu(){H.timer&&=(clearInterval(H.timer),null);try{H.node?.port?.close?.()}catch{}try{H.node?.disconnect?.()}catch{}try{H.mute?.disconnect?.()}catch{}try{H.source?.disconnect?.()}catch{}try{H.stream?.getTracks?.().forEach(e=>e.stop())}catch{}try{H.ctx?.close?.()}catch{}H.node=null,H.mute=null,H.source=null,H.stream=null,H.ctx=null}function Nu(){H.finishWaitTimer&&=(clearTimeout(H.finishWaitTimer),null),H.phase=`idle`}function Pu(){let e=()=>{let e=Date.now()-H.startedAt;H.timerEl&&(H.timerEl.textContent=Zl(e));let t=H.status;e>=(t&&t.maxRecordingMs||300*1e3)&&Iu(`stop`)};H.timer&&clearInterval(H.timer),H.timer=setInterval(e,200),e()}async function Fu(e={}){if(H.phase!==`idle`||!H.armed&&!e.force&&(await ou(),!H.armed||H.phase!==`idle`))return!1;H.phase=`starting`,H.lastText=``,H.appliedText=``,H.openText=``,H.draft=cu(),H.appliedValue=H.input?H.input.value:``,H.draftSupported=!0,H.silentSince=0,H.silenceWarned=!1,gu(),hu(r(`voice.listening`)),xu(!0),Su(!0);let t=Cu();if(!t)return hu(r(`voice.failed`),`warn`),Nu(),xu(!1),Su(!1),!1;try{await ju()}catch(e){if(H.phase!==`starting`)return Mu(),!1;let n=e?.name||``,i=n===`NotAllowedError`||n===`SecurityError`;i?(hu(r(`voice.micDenied`),`warn`),_u(!0)):hu(r(`voice.failed`),`warn`),Mu(),Nu(),xu(!1),Su(!1);try{t.postMessage({type:`cancel`})}catch{}return setTimeout(()=>{H.phase===`idle`&&yu()},i?12e3:4e3),!1}if(H.phase!==`starting`)return Mu(),!1;H.startedAt=Date.now(),H.phase=`recording`,hu(r(`voice.listening`)),H.deviceFellBack&&(H.deviceFellBack=!1,hu(r(`voice.deviceFallback`),`warn`),setTimeout(()=>{H.phase===`recording`&&hu(r(`voice.listening`))},4e3)),Pu();try{t.postMessage({type:`start`,language:H.status&&H.status.language||`auto`})}catch(e){i.debug(`[Voice] post start failed:`,e?.message||e)}return!0}function Iu(e){if(H.phase!==`recording`)return;H.phase=`finalizing`;let t=Date.now()-H.startedAt;if(Mu(),xu(!1),Su(!1),e===`cancel`){try{H.port?.postMessage({type:`cancel`})}catch{}pu(),Nu(),yu();return}if(t<Jl&&!H.lastText){try{H.port?.postMessage({type:`cancel`})}catch{}pu(),hu(r(`voice.tooShort`),`warn`),Nu(),setTimeout(()=>{H.phase===`idle`&&yu()},2200);return}hu(r(`voice.transcribing`));try{H.port?.postMessage({type:`stop`})}catch{}H.finishWaitTimer&&clearTimeout(H.finishWaitTimer),H.finishWaitTimer=setTimeout(()=>{H.phase===`finalizing`&&Ru(H.lastText,{fallback:!0})},6e4)}function Lu({rollback:e=!0}={}){if(H.phase===`idle`)return!1;let t=H.phase===`recording`||H.phase===`finalizing`;if(H.phase=`finalizing`,Mu(),t)try{H.port?.postMessage({type:`cancel`})}catch{}return e&&pu(),Nu(),xu(!1),Su(!1),yu(),!0}function Ru(e,t={}){let n=Xl(e).trim();if(!n){pu(),hu(r(`voice.noResult`),`warn`),Nu(),setTimeout(()=>{H.phase===`idle`&&yu()},2200);return}if(!H.draft){let e=H.input;if(e){let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length;uu(e.value.slice(0,t)+n+e.value.slice(t),t+n.length)}hu(r(`voice.done`)),Nu(),setTimeout(()=>{H.phase===`idle`&&yu()},1200);return}let a=Array.isArray(t.texts)?t.texts.filter(e=>typeof e==`string`&&e.trim()):[];a.length>1&&!H.draft.items.some(e=>e.id!==null||e.state===`locked`)&&(H.draft.items=a.map((e,t)=>({id:t+1,text:e,state:`refined`}))),H.draft.items.length===0&&(H.draft.items=[{id:null,text:n,state:`refined`}]);let{items:o,changed:s,takeAll:c}=Hl(H.draft.items,n);H.draft.items=o,du(!0),c&&i.debug(`[Voice] final text took over the whole draft`),H.draft=null,H.lastText=``,H.appliedText=``,H.openText=``,Nu(),hu(s>0?r(`voice.refineCorrected`,{n:s}):r(`voice.done`)),setTimeout(()=>{H.phase===`idle`&&yu()},s>0?1800:1200)}function zu(e){if(!(!e||typeof e.type!=`string`)){if(e.type===`ready`){e.draft===!1&&H.phase===`recording`&&i.debug(`[Voice] online model missing, draft disabled`);return}if(e.type===`partial`){if(H.phase!==`recording`&&H.phase!==`finalizing`)return;H.lastText=Xl(e.text),fu(typeof e.open==`string`?e.open:H.lastText);return}if(e.type===`endpoint`)return H.phase!==`recording`&&H.phase,void 0;if(e.type===`sentence`){if(H.phase!==`recording`&&H.phase!==`finalizing`||!H.draft||typeof e.id!=`number`)return;let t=typeof e.refined==`string`&&e.refined?e.refined:null,n=Array.isArray(H.draft.items)?H.draft.items:[],i=n.findIndex(e=>e.id===null),a=n;if(!t&&i>=0){let t=n[i];a=n.map((n,r)=>r===i?t.state===`locked`?{...n,id:e.id}:{id:e.id,text:Xl(e.draft)||n.text,state:`draft`}:n),H.openText=``}if(t&&(a.some(t=>t.id===e.id)?a=Bl(a,{id:e.id,text:t}).map(t=>t.id===e.id&&t.state!==`locked`?{...t,state:`refined`}:t):a.some(e=>e.id===null)||(a=a.concat([{id:e.id,text:t,state:`refined`}]))),a!==n&&(H.draft.items=a,du()),t&&H.phase===`recording`){let e=H.draft.items.filter(e=>e.id!==null&&e.state===`refined`).length;hu(r(`voice.refineListening`,{n:e}))}return}if(e.type===`refine`){e.enabled===!1&&(H.phase===`recording`||H.phase===`finalizing`)&&hu(r(`voice.refineDegraded`),`warn`);return}if(e.type===`final`){if(H.phase!==`recording`&&H.phase!==`finalizing`)return;Ru(e.text||H.lastText,{fallback:e.fallback===!0,texts:e.texts});return}if(e.type===`closed`){H.phase===`finalizing`&&Ru(H.lastText,{fallback:!0});return}if(e.type===`error`){let t=e.code||`internal`;if(t===`max_duration`){H.phase===`recording`&&Iu(`stop`),hu(r(`voice.maxDuration`),`warn`);return}hu(t===`busy`?r(`voice.busy`):t===`model_missing`?`${r(`voice.modelMissing`)} — ${r(`voice.modelMissingHelp`)}`:r(`voice.failed`),`warn`),Mu(),(H.phase===`recording`||H.phase===`finalizing`)&&pu(),Nu(),xu(!1),Su(!1),t===`model_missing`&&ou(),setTimeout(()=>{H.phase===`idle`&&yu()},3500)}}}async function Bu(){return H.phase===`recording`?(Iu(`stop`),!0):H.phase===`starting`||H.phase===`finalizing`?!1:Fu()}function Vu(){return H.phase===`recording`||H.phase===`starting`||H.phase===`finalizing`}function Hu(){return Vu()?Lu({rollback:!0}):!1}function Uu(){return H.phase===`idle`?!1:Lu({rollback:!1})}async function Wu(){try{let e=(await chrome.storage.session?.get?.(`pendingVoiceStart`))?.pendingVoiceStart;return!(!e||(await chrome.storage.session.remove(`pendingVoiceStart`),typeof e!=`number`||Date.now()-e>Wl))}catch{return!1}}function Gu(){if(!H.btn)return;let e=[`Alt+V`];H.shortcutCfg.rightAlt&&e.push(r(`voice.keyRightAlt`)),H.shortcutCfg.rightCtrl&&e.push(r(`voice.keyRightCtrl`));let t=r(`voice.btnTitle`,{keys:e.join(` / `)});H.btn.title=t,H.btn.setAttribute(`aria-label`,t)}async function Ku(){if(H.shortcutCfg=await ke(),H.shortcutTrigger||=Oe(()=>H.shortcutCfg),Gu(),H.shortcutBound)return;H.shortcutBound=!0,document.addEventListener(`keydown`,e=>{H.shortcutTrigger?.onKeyDown(e)===`cancel`&&e.preventDefault()},!0),document.addEventListener(`keyup`,e=>{H.shortcutTrigger?.onKeyUp(e)===`trigger`&&(!H.armed&&H.phase===`idle`||(e.preventDefault(),Bu()))},!0),window.addEventListener(`blur`,()=>{H.shortcutTrigger?.reset()}),De(e=>{H.shortcutCfg=e,Gu()});let e=async()=>{try{let e=await ke();if(e.rightAlt===H.shortcutCfg.rightAlt&&e.rightCtrl===H.shortcutCfg.rightCtrl)return;H.shortcutCfg=e,Gu()}catch{}};window.addEventListener(`focus`,()=>{e()}),document.addEventListener(`visibilitychange`,()=>{document.hidden||e()})}async function qu(e={}){if(H.input=document.getElementById(`userInput`),H.btn=document.getElementById(`voiceInputBtn`),H.bar=document.getElementById(`voiceRecorderBar`),H.wave=document.getElementById(`voiceWave`),H.timerEl=document.getElementById(`voiceTimer`),H.statusEl=document.getElementById(`voiceStatusText`),H.permBtn=document.getElementById(`voicePermBtn`),H.adjustInputHeight=typeof e.adjustInputHeight==`function`?e.adjustInputHeight:null,!H.input||!H.btn){i.debug(`[Voice] input or button missing, skip init`);return}mu(),xu(!1),hu(r(`voice.listening`)),await Ku(),H.btn.addEventListener(`click`,e=>{e.preventDefault(),Bu()}),document.getElementById(`voiceCancelBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),Lu({rollback:!0})}),document.getElementById(`voiceDoneBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),Iu(`stop`)}),H.permBtn?.addEventListener(`click`,e=>{e.preventDefault();try{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`asr`}).catch?.(()=>{})}catch{}hu(r(`voice.micDeniedHelp`),`warn`),_u(!1)}),H.input.addEventListener(`input`,()=>{H.programmatic||(H.phase===`recording`||H.phase===`finalizing`)&&su()}),chrome.runtime.onMessage.addListener((e,t,n)=>e?.type===`VOICE_TOGGLE`?(Bu(),n?.({success:!0}),!1):(e?.type===`ASR_STATUS_CHANGED`&&ou(),!1)),window.addEventListener(`pagehide`,()=>{Uu()}),document.addEventListener(`visibilitychange`,()=>{document.hidden&&H.phase===`recording`&&Uu()}),await ou()&&await Wu()&&setTimeout(()=>{Bu()},220)}var Ju=`panel_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8),Yu=new Set,Xu=new Set,Zu=null,Qu=new Map,$u=`queue-context-cleared`,ed=`queue-context-restored`;function td(e){Zu=e}function nd(e){return C.generatingSessionIds.has(e||C.activeSessionId)}function rd(){return{quotedContextText:C.quotedContextText||``,selectedContextText:C.selectedContextText||``,selectedSkills:(C.selectedSkills||[]).slice(),selectedMcpServices:(C.selectedMcpServices||[]).slice(),knowledgeRefs:(C.knowledgeRefs||[]).slice(),selectedPage:C.selectedPage?{...C.selectedPage}:null,attachedImages:(C.attachedImages||[]).slice(),attachedFiles:(C.attachedFiles||[]).slice()}}function id(e){return e?e.attachmentSummary||(e.attachedImages||[]).length||(e.attachedFiles||[]).length?!0:!!(e.quotedContextText&&e.quotedContextText.trim()||e.selectedContextText&&e.selectedContextText.trim()||(e.selectedSkills||[]).length||(e.selectedMcpServices||[]).length||(e.knowledgeRefs||[]).length||e.selectedPage):!1}function ad(){return id(rd())}function od(e){let t=e||{},n=(t.attachedImages||[]).length>0,i=(t.attachedFiles||[]).length>0;return n&&i?r(`sidePanel.defaultPromptAttachments`):n?r(`sidePanel.defaultPromptImage`):i?r(`sidePanel.defaultPromptFile`):(t.knowledgeRefs||[]).length>0?r(`sidePanel.defaultPromptKnowledge`):t.selectedPage?r(`sidePanel.defaultPromptPage`):t.quotedContextText&&t.quotedContextText.trim()||t.selectedContextText&&t.selectedContextText.trim()?r(`sidePanel.defaultPromptSelection`):(t.selectedSkills||[]).length>0||(t.selectedMcpServices||[]).length>0?r(`sidePanel.defaultPromptContext`):``}function sd(){let e=rd();return id(e)&&ld(),e}function cd(e){e&&(e.quotedContextText&&(C.quotedContextText=e.quotedContextText),e.selectedContextText&&(C.selectedContextText=e.selectedContextText),(e.selectedSkills||[]).length&&(C.selectedSkills=e.selectedSkills.slice()),(e.selectedMcpServices||[]).length&&(C.selectedMcpServices=e.selectedMcpServices.slice()),(e.knowledgeRefs||[]).length&&(C.knowledgeRefs=e.knowledgeRefs.slice()),e.selectedPage&&(C.selectedPage={...e.selectedPage}),(e.attachedImages||[]).length&&(C.attachedImages=e.attachedImages.slice()),(e.attachedFiles||[]).length&&(C.attachedFiles=e.attachedFiles.slice()))}function ld(){let e=(C.attachedImages||[]).length>0;if(C.quotedContextText=``,C.selectedContextText=``,C.selectedSkills=[],C.selectedMcpServices=[],C.knowledgeRefs=[],C.selectedPage=null,C.attachedImages=[],C.attachedFiles=[],e){let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}document.dispatchEvent(new CustomEvent($u))}var ud=new Set([`pending`,`extracting`]);function dd(){return(C.attachedFiles||[]).some(e=>ud.has(e&&e.status))}function fd(e){let t=e&&e.attachedImages||[],n=(e&&e.attachedFiles||[]).map(e=>{if(!e||typeof e.dataUrl!=`string`||!e.dataUrl.startsWith(`blob:`))return e;let t={...e};return delete t.dataUrl,t}),r={...e||{}};return delete r.attachedImages,delete r.attachedFiles,r.attachmentSummary=Ur({attachedImages:t,attachedFiles:n}),{light:r,heavy:t.length||n.length?{images:t,files:n}:null}}async function pd(e){if(!e)return{ok:!1,attachments:!1,wantsAttachments:!1};let t=await Gr(e.id)||Qu.get(e.id)||null,n=!!(e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary);return cd({...e.contextSnapshot||{},attachedImages:t&&t.images||[],attachedFiles:t&&t.files||[]}),document.dispatchEvent(new CustomEvent(ed,{detail:{snapshot:e.contextSnapshot||{}}})),{ok:!0,attachments:!!t,wantsAttachments:n}}async function md(e){return e?(Qu.delete(e),Kr(e)):!1}async function hd({autoDrain:e=!0}={}){let t=document.getElementById(`userInput`),n=(t?.value||``).trim()||od(rd());if(!n)return{ok:!1,error:`empty`};Uu();let i=C.activeSessionId;if(!i)return F(r(`queue.noSession`),`error`),{ok:!1,error:`missing_session`};if(dd())return F(r(`queue.filesStillExtracting`),`warning`,4e3),{ok:!1,error:`files_extracting`};let a=sd(),{light:o,heavy:s}=fd(a),c=await vr({sessionId:i,text:n,contextSnapshot:o,hasContext:id(o),attachmentSummary:o.attachmentSummary,source:`manual`});return c.ok?(s&&((await Wr(c.item.id,i,s)).ok||(Qu.set(c.item.id,s),F(r(`queue.attachmentsVolatile`),`warning`,5e3))),t&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus()),F(r(`queue.enqueued`,{position:c.position}),`success`),document.dispatchEvent(new CustomEvent(`queue-enqueued`,{detail:{sessionId:i,item:c.item}})),e&&!nd(i)&&!_r(i)&&_d(i),c):(cd(a),document.dispatchEvent(new CustomEvent(ed,{detail:{snapshot:a}})),c.error===`queue_full`?F(r(`queue.queueFull`,{limit:c.limit}),`warning`):F(r(`queue.enqueueFailed`),`error`),c)}async function gd(e){try{let{list:t}=await ti(),n=(t||[]).find(t=>t.id===e);return n?{messageHistory:Array.isArray(n.messageHistory)?n.messageHistory.slice():[],model:n.model,useTools:n.useTools,enabledTools:Array.isArray(n.enabledTools)?n.enabledTools.slice():n.enabledTools,agentId:n.agentId,temperature:n.temperature,topP:n.topP,contextCompaction:n.contextCompaction,workdir:n.workdir||null,workdirAgentId:n.workdirAgentId||null}:null}catch(e){return i.warn(`[QueueRunner] load session state failed:`,e?.message||e),null}}async function _d(e){let t=e||C.activeSessionId;if(!(!t||!Zu)){if(Yu.has(t)){Xu.add(t);return}Yu.add(t);try{do Xu.delete(t),await vd(t);while(Xu.has(t)&&!_r(t))}finally{Yu.delete(t)}}}async function vd(e){if(nd(e)||_r(e))return;let t=pr(e);if(!t)return;if((t.attempts||0)>=5){await wr(e,t.id,{status:L.FAILED,note:`too_many_attempts`}),F(r(`queue.tooManyAttempts`,{count:5}),`error`,5e3);return}if(!await Ar(e,t.id,Ju)){i.debug(`[QueueRunner] lease held by another panel, skip:`,t.id);return}await xr(e,t.id,L.DISPATCHING,{attempts:(t.attempts||0)+1,lastError:null});let n=await Gr(t.id)||Qu.get(t.id)||null;Qu.delete(t.id);let a=!!t.attachmentSummary&&!n;a&&F(r(`queue.attachmentsMissing`),`warning`,5e3);let o={quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,...t.contextSnapshot||{},attachedImages:n&&n.images||[],attachedFiles:n&&n.files||[]},s=e===C.activeSessionId,c=null;if(!s&&(c=await gd(e),!c)){let t=await jr(e);t&&i.warn(`[QueueRunner] dropped queue of deleted session:`,e,t);return}let l={ok:!0};try{let n={text:t.text,fromQueue:!0,sessionId:e,context:o};s||(n.sessionState=c),l=await Zu(n)||{ok:!0}}catch(e){l={ok:!1,reason:e?.message||`dispatch_error`},i.error(`[QueueRunner] dispatch failed:`,e?.message||e)}hr(e,t.id)?l.ok===!1?l.delivered?(await wr(e,t.id,{status:L.FAILED,note:l.reason||`failed`}),await Kr(t.id)):(await Cr(e,t.id,`dispatch_failed`,l.reason||`dispatch_failed`),Xu.delete(e)):(await wr(e,t.id,{status:L.DONE,note:a?`relayed_no_attachments`:`relayed`}),await Kr(t.id)):i.debug(`[QueueRunner] item removed during dispatch, drop result:`,t.id)}var yd=new Set;function bd(e){let t=e||C.activeSessionId;return t?(yd.add(t),t):null}function xd(e){let t=e||C.activeSessionId;return!!(t&&pr(t))}async function Sd(e){let t=e||C.activeSessionId;t&&(yd.delete(t),await kr(t),await _d(t))}function Cd(e){_r(e)||_d(e)}var wd=new Map,Td=new Set,Ed=new Map,Dd=new Map;function Od(e){let t=e&&e.attachmentSummary;return t?(t.imageCount||0)>0||(t.fileCount||0)>0:!1}function kd(e,t){return`${e}\u0000${t}`}function Ad(e,t){let n=kd(e,t),r=wd.get(n);r&&(clearTimeout(r),wd.delete(n))}async function jd(e,t,n,r){Ad(e,t);let i=hr(e,t);!i||i.status!==L.INJECTING||(await Cr(e,t,n,n),r&&F(r,`warning`,4e3))}function Md(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,r(e))},o=setTimeout(()=>a(null),2e3);try{chrome.runtime.sendMessage({type:`INJECT_MESSAGE`,sessionId:e,itemId:t,text:n},e=>{if(clearTimeout(o),chrome.runtime.lastError){a(null);return}a(e||null)})}catch{clearTimeout(o),a(null)}})}async function Nd(e,t,n={}){let i=t||C.activeSessionId,a=n.auto===!0;if(!i||!e)return{ok:!1,error:`missing_session`};let o=hr(i,e);if(!o)return{ok:!1,error:`not_found`};if(o.status!==L.QUEUED)return{ok:!1,error:`not_queued`};if(Od(o))return a||F(r(`queue.injectNoAttachments`),`warning`,4e3),{ok:!1,error:`has_attachments`};let s=kd(i,e);if(Td.has(s))return{ok:!1,error:`in_flight`};Td.add(s);try{await Sr(i,e),wd.set(s,setTimeout(()=>{jd(i,e,`timeout`,r(`queue.injectTimeout`))},Ln));let t=await Md(i,e,o.text);if(!t)return{ok:!0,pending:!0};if(!t.accepted){let n=t.reason||`rejected`;return await jd(i,e,n,r(n===`no_running_task`?`queue.injectNoTask`:`queue.injectFailed`)),{ok:!1,error:n}}return a?i===C.activeSessionId&&F(r(`queue.autoCarried`,{iteration:n.iteration??`?`}),`success`,2500):F(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0}}finally{Td.delete(s)}}function Pd(e){let t=document.getElementById(`userInput`);t&&t.value.trim()===e&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus())}async function Fd(e){let t=C.activeSessionId,n=String(e||``).trim();if(!t||!n)return{ok:!1,error:`empty`};if(Uu(),!nd(t))return F(r(`queue.injectNoTask`),`warning`,3e3),{ok:!1,error:`no_running_task`};let i=`adhoc_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,7),a=setTimeout(()=>{Ed.has(i)&&(Ed.delete(i),F(r(`queue.injectTimeoutAdhoc`),`warning`,4e3))},Ln);Ed.set(i,{text:n,timer:a});let o=await Md(t,i,n);return o&&!o.accepted?(clearTimeout(a),Ed.delete(i),F(o.reason===`no_running_task`?r(`queue.injectNoTask`):r(`queue.injectFailed`),`warning`,4e3),{ok:!1,error:o.reason}):(o&&o.accepted&&F(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0})}function Id(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=0;for(let r of n){let n=Ed.get(r);if(n){clearTimeout(n.timer),Ed.delete(r),Pd(n.text);continue}Ad(t,r),hr(t,r)&&(i++,wr(t,r,{status:L.INJECTED,note:`injected`,callId:e.callId||null,iteration:e.iteration??null}))}i>0&&t===C.activeSessionId&&F(r(`queue.injected`),`success`,2500),document.dispatchEvent(new CustomEvent(`queue-injected`,{detail:{sessionId:t,items:n,iteration:e.iteration??null}}))}function Ld(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=e.reason||`rejected`,a=r(i===`task_ended`?`queue.injectNoTask`:`queue.injectFailed`);for(let e of n){let r=Ed.get(e);if(r){clearTimeout(r.timer),Ed.delete(e);continue}jd(t,e,i,e===n[0]?a:null)}}function Rd(e){let t=e?.sessionId;if(!t||e.isSubtask===!0||_r(t))return;let n=Pl(e.executionLog);if(!n)return;let r=pr(t),a=r&&!Od(r)?r:null,o=C.chatConfig||{},s=Fl({tracker:Dd.get(t),callId:e.callId||null,iteration:n,everyN:o.queueAutoCarryEveryNIterations,enabled:o.queueAutoCarry!==!1,hasCandidate:!!a});if(Dd.set(t,s.tracker),!s.carry)return;i.debug(`[QueueRunner] auto carry item`,a.id,`at iteration`,n,`session`,t);let c=e.callId||null;Nd(a.id,t,{auto:!0,iteration:n}).then(e=>{!e||e.ok!==!0||Dd.set(t,Il(Dd.get(t),{callId:c}))})}function zd(e){!e||typeof e!=`object`||(e.type===`INJECT_ABSORBED`?Id(e):e.type===`INJECT_REJECTED`?Ld(e):e.type===`EXECUTION_STATUS_UPDATE`&&Rd(e))}async function Bd(){try{if(ar()){i.warn(`[QueueRunner] skip attachment prune in degraded mode`);return}let e=new Set;for(let t of gr())for(let n of lr(t))e.add(n.id);let t=await Jr(e);t&&i.debug(`[QueueRunner] pruned orphan attachments:`,t)}catch(e){i.warn(`[QueueRunner] prune orphan attachments failed:`,e?.message||e)}}var Vd=!1,Hd=null,Ud=[];function Wd(e,t){document.addEventListener(e,t),Ud.push([e,t])}var Gd=1500;function Kd(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,t(e))},i=setTimeout(()=>r(null),Gd);try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`,sessionId:e},e=>{if(clearTimeout(i),chrome.runtime.lastError){r(null);return}r(!!(e&&e.running))})}catch{clearTimeout(i),r(null)}})}async function qd(){if(!C.activeSessionId)return!1;let e=gr();if(e.length===0)return!0;let t=!1;for(let n of e){if(_r(n)||nd(n)||!pr(n))continue;let e=await Kd(n);if(e===null){t=!0;continue}if(!e&&!(_r(n)||nd(n)))return await _d(n),!0}return!t}function Jd(){if(Hd)return;let e=0,t=async()=>{if(Hd=null,++e>25)return;let n=!1;try{n=await qd()}catch(e){i.warn(`[QueueRunner] auto-resume attempt failed:`,e?.message||e)}n||(Hd=setTimeout(t,800))};Hd=setTimeout(t,300)}async function Yd({autoResume:e=!0}={}){Vd||(Vd=!0,await or(),sr(),Bd(),Al(Cd),typeof chrome<`u`&&chrome.runtime?.onMessage?.addListener&&chrome.runtime.onMessage.addListener(zd),Wd(`task-stop-requested`,e=>{let t=e?.detail?.sessionId||C.activeSessionId;if(t){if(yd.delete(t)){kr(t).then(()=>_d(t));return}Or(t,`user_stopped`)}}),Wd(`generating-state-changed`,()=>{let e=C.activeSessionId;if(e){if(C.isGenerating&&_r(e)){kr(e);return}for(let e of gr())if(!(_r(e)||nd(e))&&pr(e)){_d(e);break}}}),Wd(`session-switched`,()=>Jd()),Wd(`visibilitychange`,()=>{document.visibilityState===`visible`&&Jd()}),e&&Jd())}async function Xd(e){let t=e||C.activeSessionId;t&&(await kr(t),await _d(t))}var Zd=[/(?:按|按照|以|用|走|使用|开启|启用|切换?到)\s*(?:goal|目标)\s*模式/i,/(?:进入|改成|改为|设为|设置为|切换到)\s*(?:goal|目标)\s*模式/i,/\b(?:in|use|using|enable|enter|switch\s+to|with)\s+(?:the\s+)?goal\s+mode\b/i,/(?:无人值守|不用管我|别停下来|不要停|直到(?:我|你)(?:叫停|喊停))/,/\bunattended\b|\bwithout\s+(?:me|supervision)\b|\bdon'?t\s+stop\s+until\b/i,/(?:持续|一直|连续)(?:执行|跑|做|干|尝试|迭代)\s*(?:到|直到)/,/(?:跑到|做到|干到|做到)(?:完成|通过|结束|成功)/,/\bkeep\s+(?:working|going|trying|iterating)\s+until\b/i,/\brun\s+until\s+(?:done|complete|passing|it\s+passes)\b/i],Qd=[/直到\s*[^。;;\n]{1,40}?(?:全部|都)?(?:通过|完成|跑通|变绿)/,/(?:确保|保证)\s*[^。;;\n]{1,40}?(?:通过|跑通|可用)/,/\buntil\s+[^.;\n]{1,40}?(?:pass|passes|green|works)\b/i],$d=/(?:不要|不用|不必|无需|取消|关闭|停用|停止|退出|不按|不以|别|不)\s*$/,ef=/\b(?:do\s+not|don'?t|does\s+not|doesn'?t|never|avoid|without|no\s+need\s+to)\s+(?:(?:use|using|enable|enabling|enter|entering|switch(?:ing)?\s+to|turn\s+on|activate|run(?:\s+in)?|go(?:\s+with)?)\s*)?$/i,tf=2e3,nf=40;function rf(e,t,n){let r=[];for(let i of t){let t=i.flags.includes(`g`)?i.flags:`${i.flags}g`,a=new RegExp(i.source,t),o;for(;(o=a.exec(e))!==null&&o[0].length!==0;){let t=e.slice(Math.max(0,o.index-nf),o.index);if(!(n&&($d.test(t)||ef.test(t)))&&(r.push(o[0].trim()),o[0].length===0))break}}return r}function af(e){let t={detected:!1,strength:`none`,matches:[]};if(typeof e!=`string`)return t;let n=e.trim();if(!n)return t;let r=n.slice(0,tf),i=rf(r,Zd,!0);if(i.length>0)return{detected:!0,strength:`strong`,matches:of(i).slice(0,3)};let a=rf(r,Qd,!0);return a.length>0?{detected:!1,strength:`weak`,matches:of(a).slice(0,3)}:t}function of(e){let t=new Set,n=[];for(let r of e){let e=r.toLowerCase();t.has(e)||(t.add(e),n.push(r))}return n}function sf(e){if(typeof e!=`string`)return``;let t=e,n=rf(e.slice(0,tf),Zd,!0);for(let e of n)e&&(t=t.replace(e,` `));return t=t.replace(/^[\s,,。.、::;;-]+/,``).trim(),t||e.trim()}var cf={active:`goal.statusActive`,paused:`goal.statusPaused`,achieved:`goal.statusAchieved`,unmet:`goal.statusUnmet`,budget_limited:`goal.statusBudgetLimited`,cleared:`goal.statusCleared`},lf=new Set([`achieved`,`unmet`,`cleared`]),U=null;function uf(e){return document.getElementById(e)}function df(e){let t=cf[e];return t?r(t):String(e||``)}function ff(e){return!!e&&lf.has(e.status)}function pf(e){return new Promise(t=>{try{chrome.runtime.sendMessage(e,e=>{if(chrome.runtime.lastError){i.debug(`[GoalPanel] message failed:`,chrome.runtime.lastError.message),t(null);return}t(e||null)})}catch(e){i.debug(`[GoalPanel] message threw:`,e?.message),t(null)}})}function mf(e){return pf({type:`SET_GOAL`,...e})}function hf(){if(!U)return;let e=C.goalSnapshot,t=C.goalMode;U.toggle.checked=t;let n=t&&!!e&&(e.status===`paused`||e.status===`budget_limited`);U.group&&(U.group.dataset.goalIdle=n?`1`:``);let i=t||e&&!ff(e);if(U.bar.style.display=i?``:`none`,!i)return;if(U.bar.dataset.status=e?e.status:`none`,U.status.textContent=e?df(e.status):``,U.status.style.display=e?``:`none`,e){U.objective.textContent=e.objective||``,U.objective.title=e.objective||``;let t=M(e,r);n&&e.status===`paused`&&t.push(r(`goal.pausedHintInline`)),U.meta.textContent=t.join(` · `)}else U.objective.textContent=r(`goal.startHint`),U.objective.title=``,U.meta.textContent=``;let a=!!e&&e.status===`active`&&e.autoApprove===!0;U.approve.style.display=a?``:`none`;let o=!!e&&e.status===`active`,s=!!e&&(e.status===`paused`||e.status===`budget_limited`);U.pause.style.display=o?``:`none`,U.resume.style.display=s?``:`none`,U.edit.style.display=e?``:`none`,U.clear.style.display=e?``:`none`}function gf(){return C.activeSessionId||null}async function _f(e=gf()){if(!e)return C.goalSnapshot=null,hf(),null;let t=await pf({type:`GET_GOAL`,sessionId:e});return e===gf()?(C.goalSnapshot=t?.goal||null,hf(),C.goalSnapshot):null}var vf=null;async function yf(){return vf||(vf=await new Promise(e=>{try{chrome.storage.local.get([`goalConfig`],t=>e(t?.goalConfig||{}))}catch(t){i.debug(`[GoalPanel] read goalConfig failed:`,t?.message),e({})}}),vf)}async function bf(){let e=uf(`goalGroup`);if(!e)return;let t=await yf();e.style.display=t.enabled===!1?`none`:``}async function xf({sessionId:e=gf(),text:t=``,attachments:n=[]}={}){if(!e||!String(t||``).trim())return null;let i=await yf(),a=!!C.goalMode;if(i.enabled===!1)return a&&F(r(`goal.disabledHint`),`warning`),null;let o=t;if(!a){if(i.intentDetection===!1)return null;let e=af(t);if(!e.detected)return e.strength===`weak`&&F(r(`goal.intentHint`),`info`,6e3),null;o=String(sf(t)||``).trim()||t}let s=await mf({sessionId:e,action:`set`,objective:o,attachments:Array.isArray(n)?n:[],createdBy:a?`toggle`:`intent`,autoApprove:a});return!s||s.success===!1?(s?.disabled&&F(r(`goal.disabledHint`),`warning`),null):(a||F(r(`goal.intentDetected`),`info`,6e3),e===gf()?(C.goalSnapshot=s.goal||null,hf(),s.goal||null):s.goal||null)}function Sf(e={}){let t=[],n=Array.isArray(e.attachedImages)?e.attachedImages.length:0;n>0&&t.push({kind:`image`,name:r(`goal.attachmentImage`,{count:n})});for(let n of Array.isArray(e.attachedFiles)?e.attachedFiles:[])!n||n.status!==`done`||!n.name||t.push({kind:`file`,name:String(n.name),detail:n.agentPath?`workspace file`:`inline text`});let i=e.selectedPage;i&&(i.title||i.url)&&t.push({kind:`page`,name:String(i.title||i.url),detail:i.id==null?``:`tab ${i.id}`});for(let n of Array.isArray(e.knowledgeRefs)?e.knowledgeRefs:[])n&&n.name&&t.push({kind:`knowledge`,name:String(n.name)});return t}function Cf(){C.goalSnapshot=null,hf()}function wf(){return hf(),_f()}function Tf(e=``){return new Promise(t=>{let n=document.createElement(`div`);n.className=`modal-overlay show`,n.innerHTML=`
|
|
94
|
+
`}).join(``),t.querySelectorAll(`.prototype-library-item`).forEach(e=>{let t=e.querySelector(`.prototype-library-item-info`),n=e.querySelector(`.prototype-library-item-open`),a=e.querySelector(`.prototype-library-item-local-open`),o=e.querySelector(`.prototype-library-item-optimize`),s=e.querySelector(`.prototype-library-item-delete`),c=e.querySelector(`.prototype-library-item-download`);t&&t.addEventListener(`click`,()=>{let t=e.dataset.id;Cc(t)}),n&&n.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.id;Cc(n)}),a&&a.addEventListener(`click`,e=>{e.stopPropagation();let t=a.dataset.path;chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:t},e=>{e?.success||i.error(`[SidePanel] local browseropen failed:`,e?.error)})}),o&&o.addEventListener(`click`,t=>{t.stopPropagation();let n=o.dataset.id;kc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`)),Oc()}),s&&s.addEventListener(`click`,t=>{t.stopPropagation();let n=s.dataset.id;jc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`))}),c&&c.addEventListener(`click`,e=>{e.stopPropagation();let t=c.dataset.id;Ac(t)})})))}function Dc(e){let t=()=>{let t=document.getElementById(`prototypeLibrarySearch`),n=document.getElementById(`prototypeLibrarySort`),r=(t?.value||``).trim().toLowerCase(),i=n?.value||`createdAt_desc`,a=e;r&&(a=e.filter(e=>(e.title||``).toLowerCase().includes(r)||(e.description||``).toLowerCase().includes(r)));let[o,s]=i.split(`_`);a=[...a].sort((e,t)=>{let n;return n=o===`title`?(e.title||``).localeCompare(t.title||``,`zh-CN`):(e.createdAt||0)-(t.createdAt||0),s===`desc`?-n:n}),Ec(a)},n=document.getElementById(`prototypeLibrarySearch`),r=document.getElementById(`prototypeLibrarySort`);if(n){let e=n.cloneNode(!0);n.parentNode.replaceChild(e,n),e.addEventListener(`input`,t)}if(r){let e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener(`change`,t)}}function Oc(){let e=document.getElementById(`prototypeLibraryModal`);e&&e.classList.remove(`show`),i.debug(`[SidePanel] prototype page libraryhidden`)}function kc(e,t){let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),i.debug(`[SidePanel] from prototype page librarycontinue optimizeprototype:`,e)}async function Ac(e){try{let t=await D(e);if(!t||!t.html){i.error(`[SidePanel] download prototype failed:not foundprototype`,e);return}let n=_c(t.html),r=new Blob([n],{type:`text/html`}),a=URL.createObjectURL(r),o=document.createElement(`a`);o.href=a,o.download=(t.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a),i.debug(`[SidePanel] prototype fromprototypelibrarydownload:`,o.download)}catch(e){i.error(`[SidePanel] download prototype failed:`,e)}}async function jc(e,t){if(await Mc(r(`uiProto.confirmDeleteTitle`),r(`uiProto.confirmDeleteMessage`,{title:t}),r(`common.delete`)))try{let t=await D(e);await x(e),i.debug(`[SidePanel] prototype deleted:`,e),t?.localPath&&chrome.runtime.sendMessage({type:`DELETE_LOCAL_PROTOTYPE`,path:t.localPath},e=>{e?.success?i.debug(`[SidePanel] local prototypefile deleted:`,t.localPath):i.warn(`[SidePanel] local prototypefiledelete failed:`,e?.error)}),Tc()}catch(e){i.error(`[SidePanel] delete prototype failed:`,e),alert(r(`uiProto.deleteFailed`,{message:e.message}))}}function Mc(e,t,n=r(`common.confirm`)){return new Promise(r=>{let i=document.getElementById(`genericConfirmModal`),a=document.getElementById(`genericConfirmTitle`),o=document.getElementById(`genericConfirmMessage`),s=document.getElementById(`genericConfirmOkBtn`),c=document.getElementById(`genericConfirmCancelBtn`);if(!i){r(confirm(t));return}a.textContent=e,o.textContent=t,s.textContent=n;let l=()=>{i.classList.remove(`show`),s.removeEventListener(`click`,u),c.removeEventListener(`click`,d)},u=()=>{l(),r(!0)},d=()=>{l(),r(!1)};s.addEventListener(`click`,u),c.addEventListener(`click`,d),i.classList.add(`show`)})}function Nc(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function Pc(e){if(!e)return``;let t=new Date(e),n=new Date-t;return n<6e4?r(`uiProto.justNow`):n<36e5?r(`uiProto.minutesAgo`,{count:Math.floor(n/6e4)}):n<864e5?r(`uiProto.hoursAgo`,{count:Math.floor(n/36e5)}):t.toLocaleDateString(`zh-CN`)}function Fc(e){pc=Math.max(mc,Math.min(hc,e)),pc=Math.round(pc*100)/100;let t=document.getElementById(`prototypeIframe`),n=document.getElementById(`prototypeZoomLevel`);t&&(t.style.zoom=pc),n&&(n.textContent=Math.round(pc*100)+`%`,pc===1?n.classList.remove(`zoomed`):n.classList.add(`zoomed`))}function Ic(){Fc(pc+gc),zc()}function Lc(){Fc(pc-gc),zc()}function Rc(){Fc(1)}function zc(){let e=document.getElementById(`prototypeZoomLevel`);e&&(e.classList.add(`flash`),setTimeout(()=>e.classList.remove(`flash`),150))}function Bc(e){!e.ctrlKey&&!e.metaKey||(e.preventDefault(),e.deltaY<0?Ic():Lc())}function Vc(e){(e.ctrlKey||e.metaKey)&&e.key===`0`&&(e.preventDefault(),Rc())}function Hc(){let e=document.getElementById(`prototypeCloseBtn`);e&&e.addEventListener(`click`,yc);let t=document.getElementById(`prototypeDownloadBtn`);t&&t.addEventListener(`click`,xc);let n=document.getElementById(`prototypeOpenTabBtn`);n&&n.addEventListener(`click`,Sc);let r=document.getElementById(`prototypeLocalOpenBtn`);r&&r.addEventListener(`click`,()=>{let e=r.dataset.path;e&&chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:e},e=>{e?.success||i.error(`[SidePanel] local browseropen failed:`,e?.error)})});let a=document.getElementById(`prototypeContinueBtn`);a&&a.addEventListener(`click`,bc);let o=document.getElementById(`prototypeZoomInBtn`);o&&o.addEventListener(`click`,Ic);let s=document.getElementById(`prototypeZoomOutBtn`);s&&s.addEventListener(`click`,Lc);let c=document.getElementById(`prototypeZoomLevel`);c&&c.addEventListener(`click`,Rc);let l=document.getElementById(`prototypeContent`);l&&l.addEventListener(`wheel`,Bc,{passive:!1}),document.addEventListener(`keydown`,Vc);let u=document.getElementById(`prototypeLibraryCloseBtn`);u&&u.addEventListener(`click`,Oc),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_UI_PROTOTYPE`&&(i.debug(`[SidePanel] received showprototyperequested :`,e),e.data.localOpened?i.debug(`[SidePanel] prototype inagent-side browseropen,skip popup`):e.data.isRemoteAgent?(i.debug(`[SidePanel] remoteagent,will use browserlabelpageautoopenprototype`),wc(e.data.prototypeId)):Cc(e.data.prototypeId),n({success:!0}))}),i.debug(`[SidePanel] UI prototype moduleeventinitializing`)}var Uc={enabled:!1,thresholdRatio:.85,minPending:4,maxFailures:2};function Wc(e,t){let n=Number(e);return Number.isFinite(n)&&n>0&&n<=1?n:t}function Gc(e,t){let n=Number(e);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function Kc({enabled:e,ratio:t,thresholdRatio:n,pendingCount:r,minPending:i,isGenerating:a,isolateChat:o}={}){if(!e||a||!o)return!1;let s=Wc(n,Uc.thresholdRatio),c=Gc(i,Uc.minPending);return!Number.isFinite(t)||t<s?!1:Gc(r,0)>=c}function qc(e){let t=e?.messageHistory||[],n=e?.activeCompaction?.upToMessageId;if(!n)return t.length;let r=t.findIndex(e=>e.messageId===n);return r===-1?t.length:t.length-r-1}var Jc=0;function Yc(){Jc=0}async function Xc({state:e,getRatio:t,compact:n}={}){let r=e?.chatConfig||{},a=r.autoCompaction===!0;if(!a)return{attempted:!1,success:!1,reason:`disabled`};if(Jc>=Uc.maxFailures)return{attempted:!1,success:!1,reason:`backoff`};let o;try{o=Number(t?t():NaN)}catch(e){return i.warn(`[AutoCompaction] usage compute failed, send continues:`,e?.message),{attempted:!1,success:!1,reason:`usage_unavailable`}}let s=qc(e);if(!Kc({enabled:a,ratio:o,thresholdRatio:r.autoCompactionThreshold,pendingCount:s,isGenerating:!!e?.isGenerating,isolateChat:!!e?.isolateChat}))return{attempted:!1,success:!1,reason:`not_needed`};i.debug(`[AutoCompaction] triggered`,{ratio:o,pendingCount:s});let c=null;try{c=await n({silent:!0})}catch(e){return i.warn(`[AutoCompaction] compact threw, send continues:`,e?.message),Jc++,{attempted:!0,success:!1,reason:`exception`}}return c?.success?(Yc(),{attempted:!0,success:!0}):(Jc++,i.debug(`[AutoCompaction] skipped send:`,c?.reason),{attempted:!0,success:!1,reason:c?.reason||`failed`})}var Zc=null,Qc=`global`,$c=new Map;function el(){try{chrome.windows?.getCurrent?.().then?.(e=>{e?.id!=null&&(Zc=e.id)}).catch?.(e=>{i.debug(`[PanelContext] query current window failed:`,e?.message)})}catch(e){i.debug(`[PanelContext] init window query failed:`,e?.message)}try{chrome.storage?.local?.get?.([`sidePanelScope`],e=>{Qc=e?.sidePanelScope===`tab-specific`?`tab-specific`:`global`}),chrome.storage?.onChanged?.addListener?.((e,t)=>{t!==`local`||!e?.sidePanelScope||(Qc=e.sidePanelScope.newValue===`tab-specific`?`tab-specific`:`global`)})}catch(e){i.debug(`[PanelContext] init scope mirror failed:`,e?.message)}}function tl(){return Zc}function nl(e){e&&typeof C.currentTabId==`number`&&$c.set(e,C.currentTabId)}function rl(e,t){e&&(typeof t==`number`?$c.set(e,t):$c.delete(e))}function il(e){if(!e)return null;let t=$c.get(e);return typeof t==`number`?t:null}function al(e){let t=null;try{t=typeof document<`u`?!!document.hidden:null}catch{}return{windowId:Zc,hostTabId:il(e),scope:Qc,panelHidden:t}}var ol=0,sl=500,cl=[{frequency:523.25,startTime:0,duration:.12,type:`sine`,gain:.3},{frequency:659.25,startTime:.09,duration:.12,type:`sine`,gain:.3},{frequency:783.99,startTime:.18,duration:.22,type:`sine`,gain:.35}],ll=[{frequency:440,startTime:0,duration:.16,type:`square`,gain:.22},{frequency:349.23,startTime:.14,duration:.3,type:`square`,gain:.22}],ul=[`#FF3B30`,`#FF9500`,`#FFCC00`,`#34C759`,`#00C7BE`,`#007AFF`,`#AF52DE`,`#FF2D55`],dl=120,fl=4e3,pl=600,ml=1e3,hl=.25,gl=.99,_l=.3,vl=.6,yl=9999;function bl(){return new Promise(e=>{try{chrome.storage.local.get([`completionSoundEnabled`,`completionConfettiEnabled`],t=>{e({soundEnabled:t?.completionSoundEnabled!==!1,confettiEnabled:t?.completionConfettiEnabled!==!1})})}catch(t){i.debug(`[CompletionFeedback] read config failed, use defaults:`,t?.message),e({soundEnabled:!0,confettiEnabled:!0})}})}function xl(e){try{let t=window.AudioContext||window.webkitAudioContext;if(!t){i.debug(`[CompletionFeedback] AudioContext unavailable`);return}let n=new t;n.state===`suspended`&&typeof n.resume==`function`&&n.resume().catch(()=>{});let r=n.currentTime,a=0;for(let t of e){let e=n.createOscillator(),i=n.createGain();e.type=t.type||`sine`,e.frequency.value=t.frequency;let o=r+t.startTime,s=o+t.duration;i.gain.setValueAtTime(1e-4,o),i.gain.exponentialRampToValueAtTime(t.gain,o+.012),i.gain.exponentialRampToValueAtTime(1e-4,s),e.connect(i),i.connect(n.destination),e.start(o),e.stop(s+.02),s>a&&(a=s)}let o=Math.max(0,(a-r)*1e3)+200;setTimeout(()=>{try{n.close()}catch{}},o)}catch(e){i.debug(`[CompletionFeedback] play tone failed:`,e?.message)}}function Sl(){xl(cl),i.debug(`[CompletionFeedback] success sound played`)}function Cl(){xl(ll),i.debug(`[CompletionFeedback] failure sound played`)}function wl(){try{return typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{return!1}}function Tl(){try{if(!document.body)return;let e=window.innerWidth,t=window.innerHeight;if(e<=0||t<=0)return;let n=document.createElement(`canvas`);n.style.cssText=`position:fixed;inset:0;pointer-events:none;z-index:${yl};`;let r=window.devicePixelRatio||1;n.width=Math.floor(e*r),n.height=Math.floor(t*r),n.style.width=e+`px`,n.style.height=t+`px`,document.body.appendChild(n);let a=n.getContext(`2d`);if(!a){n.remove();return}a.scale(r,r);let o=[{x:e*.15,y:t+10,baseAngle:-Math.PI/2+_l},{x:e*.85,y:t+10,baseAngle:-Math.PI/2-_l}],s=[],c=0,l=0,u=performance.now(),d=e=>{let t=Math.min(dl,Math.floor(Math.min(e,pl)/pl*dl));for(;c<t;){let e=o[c%o.length],t=e.baseAngle+(Math.random()-.5)*vl,n=12+Math.random()*8,r=4+Math.random()*4;s.push({x:e.x+(Math.random()-.5)*20,y:e.y,vx:Math.cos(t)*n,vy:Math.sin(t)*n,size:r,color:ul[Math.floor(Math.random()*ul.length)],rotation:Math.random()*Math.PI*2,rotationSpeed:(Math.random()-.5)*.3,shape:Math.random()<.5?`rect`:`circle`}),c++}},f=r=>{let i=r-u;if(i>=fl){cancelAnimationFrame(l),n.remove();return}d(i),a.clearRect(0,0,e,t);let o=fl-ml,c=i>o?Math.max(0,1-(i-o)/ml):1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.vy+=hl,r.vx*=gl,r.vy*=gl,r.x+=r.vx,r.y+=r.vy,r.rotation+=r.rotationSpeed,r.y-r.size>t||r.x+r.size<0||r.x-r.size>e){s.splice(n,1);continue}a.save(),a.globalAlpha=c,a.translate(r.x,r.y),a.rotate(r.rotation),a.fillStyle=r.color,r.shape===`rect`?a.fillRect(-r.size/2,-r.size/2,r.size,r.size*.6):(a.beginPath(),a.arc(0,0,r.size/2,0,Math.PI*2),a.fill()),a.restore()}l=requestAnimationFrame(f)};l=requestAnimationFrame(f),i.debug(`[CompletionFeedback] confetti launched`)}catch(e){i.debug(`[CompletionFeedback] launch confetti failed:`,e?.message)}}function El(e,t,n,r){try{chrome.runtime.sendMessage({type:`TASK_FEEDBACK_NOTIFY`,success:e,sessionId:t||null,error:n||``,question:r||``,panel:al(t)})?.catch?.(()=>{})}catch(e){i.debug(`[CompletionFeedback] desktop notify failed:`,e?.message)}}async function Dl(e=null,t=``){try{let n=Date.now();if(n-ol<sl){i.debug(`[CompletionFeedback] throttled, skip`);return}ol=n;let{soundEnabled:r,confettiEnabled:a}=await bl();r&&Sl(),a&&!wl()&&Tl(),El(!0,e,``,t)}catch(e){i.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}async function Ol(e=null,t=``,n=``){try{let r=Date.now();if(r-ol<sl){i.debug(`[CompletionFeedback] throttled, skip`);return}ol=r;let{soundEnabled:a}=await bl();a&&Cl(),El(!1,e,t,n)}catch(e){i.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}var kl=new Set;function Al(e){return typeof e==`function`?(kl.add(e),()=>kl.delete(e)):()=>{}}function jl(e){let t=e||C.activeSessionId;if(t){C.generatingSessionIds.delete(t);try{$r(t)}catch(e){i.warn(`[GenerationLifecycle] markSessionCompleted failed:`,e?.message)}typeof document<`u`&&typeof CustomEvent==`function`&&(document.dispatchEvent(new CustomEvent(`generating-state-changed`)),document.dispatchEvent(new CustomEvent(`generation-ended`,{detail:{sessionId:t}})));for(let e of kl)try{e(t)}catch(e){i.error(`[GenerationLifecycle] end handler failed:`,e?.message)}}}function Ml(e){let t=Number(e);return!Number.isFinite(t)||t<=0?3:Math.min(20,Math.max(1,Math.round(t)))}function Nl(){return{callId:null,carried:0,lastIteration:null}}function Pl(e){let t=0;for(let n of e||[]){let e=Number(n&&n.iteration);Number.isFinite(e)&&e>t&&(t=e)}return t}function Fl(e){let{tracker:t,callId:n=null,iteration:r,everyN:i,enabled:a=!0,hasCandidate:o=!0}=e||{},s=t&&typeof t==`object`?{callId:t.callId??null,carried:Number(t.carried)||0,lastIteration:t.lastIteration??null}:Nl(),c=Number(r);if(!Number.isFinite(c)||c<=0)return{carry:!1,reason:`invalid_iteration`,tracker:s};let l=!!n&&!!s.callId&&n!==s.callId,u=s.lastIteration!=null&&c<s.lastIteration;if((l||u)&&(s=Nl()),n&&!s.callId&&(s={...s,callId:n}),!a)return{carry:!1,reason:`disabled`,tracker:s};if(c<2)return{carry:!1,reason:`too_early`,tracker:s};if(!o)return{carry:!1,reason:`no_candidate`,tracker:s};if(s.carried>=3)return{carry:!1,reason:`call_limit`,tracker:s};let d=Ml(i);return s.lastIteration!=null&&c-s.lastIteration<d?{carry:!1,reason:`interval_not_reached`,tracker:s}:{carry:!0,reason:`carry`,tracker:{callId:s.callId||n||null,carried:s.carried,lastIteration:c}}}function Il(e,{callId:t=null}={}){let n=e&&typeof e==`object`?e:Nl();return t&&n.callId&&t!==n.callId?n:{...n,carried:(Number(n.carried)||0)+1}}var Ll=/[\p{P}\p{S}]/gu;function Rl(e){return Array.isArray(e)?e.map(e=>e&&e.text||``).join(``):``}function zl(e){return String(e||``).replace(/[\s\u3000]/g,``).replace(Ll,``)}function Bl(e,t){if(!Array.isArray(e))return e;let n=t&&t.id,r=t&&typeof t.text==`string`?t.text:null;if(r===null||typeof n!=`number`)return e;let i=!1,a=e.map(e=>!e||e.id!==n||e.state===`locked`?e:(i=!0,{...e,text:r}));return i?a:e}function Vl(e,t,n){let r=String(t||``),i=String(n||``),a={lockedIds:[],shift:0,items:e,len:r.length};if(r===i||!Array.isArray(e)||e.length===0)return a;let o=0,s=Math.min(r.length,i.length);for(;o<s&&r[o]===i[o];)o++;let c=0,l=Math.min(r.length-o,i.length-o);for(;c<l&&r[r.length-1-c]===i[i.length-1-c];)c++;let u=o,d=r.length-c;if(u>=r.length&&d>=r.length){let t=e[e.length-1],n=t&&t.text?t.text.length:0,a=i.slice(Math.max(0,r.length-n)),o=e.map((t,n)=>n===e.length-1?{...t,text:a}:t);return{lockedIds:[t.id],shift:0,items:o,len:i.length}}let f=[],p=0;for(let t of e){let e=(t&&t.text?t.text:``).length;u<p+e&&d>p&&f.push(t.id),p+=e}if(f.length===0)return{lockedIds:[],shift:u===0?i.length-r.length:0,items:e,len:r.length};let m=i.length-r.length,h=d+m,g=e=>e<=u?e:e>=d?e+m:u+Math.min(e-u,Math.max(0,h-u)),_=0;return{lockedIds:f,shift:0,items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=g(_),r=g(_+t);return _+=t,{...e,text:i.slice(n,r)}}),len:i.length}}function Hl(e,t){if(!Array.isArray(e)||e.length===0)return{items:Array.isArray(e)?e:[],changed:0,takeAll:!1};let n=Rl(e),r=String(t||``);if(!r)return{items:e,changed:0,takeAll:!1};let i=zl(n),a=zl(r);if(i===a)return{items:e,changed:0,takeAll:!1};if(Math.abs(i.length-a.length)+Ul(i,a)>2||i.length!==a.length)return e.some(e=>e&&e.state===`locked`)?{items:e,changed:0,takeAll:!1}:{items:[{id:e[0]&&typeof e[0].id==`number`?e[0].id:null,text:r,state:`refined`}],changed:1,takeAll:!0};let o=n.split(``),s=0,c=0;for(let e=0;e<o.length;e++)zl(o[e])!==``&&(s<a.length&&o[e]!==a[s]&&(o[e]=a[s],c+=1),s+=1);if(c===0)return{items:e,changed:0,takeAll:!1};let l=o.join(``),u=0;return{items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=e&&e.state===`locked`?e.text:l.slice(u,u+t);return u+=t,e&&e.state===`locked`?e:{...e,text:n}}),changed:c,takeAll:!1}}function Ul(e,t){if(e.length!==t.length)return 2**53-1;let n=0;for(let r=0;r<e.length;r++)e[r]!==t[r]&&(n+=1);return n}n(`zh`,{voice:{start:`语音输入(开始录音)`,stop:`结束录音并转写`,recording:`正在录音`,listening:`正在聆听…`,transcribing:`正在转写…`,cancel:`取消录音`,done:`完成`,noSpeech:`没有听到声音`,noResult:`未识别到语音`,micDenied:`麦克风未授权`,micDeniedHelp:`侧边栏里浏览器不会弹授权框,请到配置页「语音输入 → 麦克风权限」授权一次`,micDeniedAction:`去授权`,micDeniedActionTitle:`打开配置页授权麦克风(侧边栏内无法弹出授权框)`,unavailable:`语音功能不可用`,modelMissing:`缺少语音模型`,modelMissingHelp:`请在配置页「语音」Tab 中导入模型包`,busy:`有语音任务正在进行`,failed:`语音识别失败`,connectionLost:`连接中断`,tooShort:`录音太短`,maxDuration:`已达单次录音时长上限,正在转写…`,unsupported:`当前浏览器不支持录音`,keyRightAlt:`右侧 Alt`,keyRightCtrl:`右侧 Ctrl`,btnTitle:`语音输入({keys})`,deviceFallback:`原麦克风不可用,已改用系统默认`,refineListening:`正在听…(已定稿 {n} 句)`,refineCorrecting:`正在校正…`,refineCorrected:`已校正 {n} 处`,refineDegraded:`本机性能有限,已关闭逐句精修(松手后仍会整体校正)`}}),n(`en`,{voice:{start:`Voice input (start recording)`,stop:`Stop and transcribe`,recording:`Recording`,listening:`Listening…`,transcribing:`Transcribing…`,cancel:`Cancel recording`,done:`Done`,noSpeech:`No sound detected`,noResult:`No speech recognised`,micDenied:`Microphone not granted`,micDeniedHelp:`The browser cannot prompt inside the side panel — grant it once in Options → Voice Input → Microphone permission`,micDeniedAction:`Grant access`,micDeniedActionTitle:`Open options to grant microphone access (the side panel cannot show the prompt)`,unavailable:`Voice input unavailable`,modelMissing:`Speech model missing`,modelMissingHelp:`Import a model pack in the Options "Voice" tab`,busy:`Another voice task is running`,failed:`Speech recognition failed`,connectionLost:`Connection lost`,tooShort:`Recording too short`,maxDuration:`Recording length limit reached, transcribing…`,unsupported:`Recording is not supported in this browser`,keyRightAlt:`Right Alt`,keyRightCtrl:`Right Ctrl`,btnTitle:`Voice input ({keys})`,deviceFallback:`Selected microphone unavailable — using the system default`,refineListening:`Listening… ({n} sentences finalized)`,refineCorrecting:`Refining…`,refineCorrected:`{n} correction(s) applied`,refineDegraded:`This machine is too slow for per-sentence refinement (the final pass still runs)`}});var Wl=15e3,Gl=16e3,Kl=2500,ql=.008,Jl=350,Yl=24,H={input:null,btn:null,bar:null,wave:null,timerEl:null,statusEl:null,permBtn:null,barEls:[],status:null,armed:!1,phase:`idle`,port:null,stream:null,ctx:null,node:null,source:null,startedAt:0,timer:null,silentSince:0,silenceWarned:!1,draft:null,lastText:``,appliedText:``,appliedValue:``,openText:``,mute:null,programmatic:!1,draftSupported:!0,finishWaitTimer:null,adjustInputHeight:null,shortcutCfg:{...je},shortcutTrigger:null,shortcutBound:!1,deviceFellBack:!1};function Xl(e){return typeof e==`string`?e:``}function Zl(e){let t=Math.max(0,Math.floor(e/1e3));return`${String(Math.floor(t/60)).padStart(2,`0`)}:${String(t%60).padStart(2,`0`)}`}function Ql(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode.apply(null,t.subarray(e,e+r));return btoa(n)}function $l(e,t,n){if(t===n)return e;let r=t/n,i=Math.floor(e.length/r),a=new Float32Array(i);for(let t=0;t<i;t++){let n=t*r,i=Math.floor(n),o=n-i,s=e[i]||0;a[t]=s+((e[i+1]===void 0?s:e[i+1])-s)*o}return a}function eu(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++){let r=e[n]<-1?-1:e[n]>1?1:e[n];t[n]=r<0?r*32768:r*32767}return t}async function tu(e=!1){try{let t=await chrome.runtime.sendMessage({type:`ASR_GET_STATUS`,force:e});if(t&&t.success&&t.status)return H.status=t.status,H.status}catch(e){i.debug(`[Voice] status fetch failed:`,e?.message||e)}return H.status=null,null}function nu(e){return!e||e.success===!1?!1:typeof e.available==`boolean`?e.available:e.deps?.ready===!0&&e.modelsReady===!0&&e.enabled===!0}function ru({value:e,draft:t,text:n,caret:r,canReplace:i=!0}){let a=typeof e==`string`?e:``;if(!t)return{value:a,caret:a.length,len:0};if(!i){let e=typeof r==`number`?Math.min(Math.max(0,r),a.length):a.length;return{value:a.slice(0,e)+n+a.slice(e),caret:e+n.length,len:0}}let o=Math.min(Math.max(0,t.start),a.length),s=Math.min(Math.max(o,t.start+t.len),a.length);return{value:a.slice(0,o)+n+a.slice(s),caret:o+n.length,len:n.length}}function iu({value:e,draft:t,canReplace:n=!0}){let r=typeof e==`string`?e:``;if(!t||!n||t.len<=0)return{value:r,caret:r.length};let i=Math.min(Math.max(0,t.start),r.length),a=Math.min(Math.max(i,t.start+t.len),r.length);return{value:r.slice(0,i)+r.slice(a),caret:i}}function au(e){return!e||e.isComposing||e.repeat?!1:e.altKey===!0&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyV`}async function ou(){return H.armed=nu(await tu()),H.btn&&(H.btn.style.display=H.armed?``:`none`),!H.armed&&H.phase!==`idle`&&Lu({rollback:!0}),H.armed}function su(){if(!H.draft||!H.input)return;let e=Rl(H.draft.items),t=H.input.value,n=Xl(H.appliedValue),r=H.draft.start,i=r+e.length,a=0;for(;a<n.length&&a<t.length&&n[a]===t[a];)a+=1;let o=0,s=Math.min(n.length-a,t.length-a);for(;o<s&&n[n.length-1-o]===t[t.length-1-o];)o+=1;let c=a;if(n.length-o<=r){H.draft.start=Math.max(0,r+(t.length-n.length));return}if(c>i)return;let l=Math.max(0,n.length-i),u=t.slice(r,Math.max(r,t.length-l)),d=Vl(H.draft.items,e,u);d.shift&&(H.draft.start+=d.shift),d.lockedIds.length!==0&&(H.draft.items=d.items.map(e=>d.lockedIds.includes(e.id)?{...e,state:`locked`}:e),H.draft.len=d.len)}function cu(){let e=H.input;if(!e)return{start:0,len:0,items:[]};let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length,n=typeof e.selectionEnd==`number`?e.selectionEnd:t;return t!==n&&e.setRangeText(``,t,n,`end`),{start:t,len:0,items:[]}}function lu(e,t){let n=Xl(e),r=Xl(t);return r?n?r.startsWith(n)?r.slice(n.length):null:r:``}function uu(e,t){let n=H.input;if(n){H.programmatic=!0,H.appliedValue=e,n.value=e;try{n.setSelectionRange(t,t)}catch{}H.programmatic=!1;try{document.dispatchEvent(new CustomEvent(`voice-draft-written`))}catch{}try{H.adjustInputHeight?.()}catch{}try{n.focus()}catch{}}}function du(e=!1){let t=H.input;if(!t||!H.draft)return;let n=Rl(H.draft.items);if(!e&&n===Xl(H.appliedText))return;let r=typeof t.selectionStart==`number`?t.selectionStart:void 0,i=H.draft.start,a=i+H.draft.len,o=ru({value:t.value,draft:{start:i,len:H.draft.len},text:n,caret:r,canReplace:H.draftSupported});typeof r==`number`&&r>i&&r<a&&(o.caret=i+Math.min(r-i,n.length)),H.draft.len=n.length,H.appliedText=n,uu(o.value,o.caret)}function fu(e){if(!H.input||!H.draft)return;let t=Array.isArray(H.draft.items)?H.draft.items:[],n=t.findIndex(e=>e.id===null),r=Xl(e);if(n>=0&&t[n].state===`locked`){let e=lu(H.openText,r);if(H.openText=r,!e)return;H.draft.items=t.map((t,r)=>r===n?{...t,text:t.text+e}:t)}else H.openText=r,H.draft.items=n>=0?t.map((e,t)=>t===n?{...e,text:r}:e):t.concat([{id:null,text:r,state:`draft`}]);du()}function pu(){let e=H.input;if(!e||!H.draft)return;let t=Array.isArray(H.draft.items)&&H.draft.items.some(e=>e.state===`locked`)?{value:e.value,caret:e.value.length}:iu({value:e.value,draft:H.draft,canReplace:H.draftSupported});if(t.value!==e.value){H.programmatic=!0,H.appliedValue=t.value,e.value=t.value;let n=Math.min(t.caret,e.value.length);try{e.setSelectionRange(n,n)}catch{}H.programmatic=!1;try{H.adjustInputHeight?.()}catch{}}H.draft=null,H.lastText=``,H.appliedText=``,H.openText=``}function mu(){if(H.wave){H.wave.textContent=``,H.barEls=[];for(let e=0;e<Yl;e++){let e=document.createElement(`i`);H.wave.appendChild(e),H.barEls.push(e)}}}function hu(e,t=``){H.statusEl&&(H.statusEl.textContent=e,H.statusEl.className=`voice-recorder-status`+(t?` is-${t}`:``))}function gu(){H.bar&&(H.bar.classList.add(`show`),H.bar.removeAttribute(`aria-hidden`))}function _u(e){H.permBtn&&(H.permBtn.style.display=e?``:`none`)}function vu(){let e=document.activeElement;if(!(!H.bar||!e||!H.bar.contains(e))){if(H.input&&typeof H.input.focus==`function`)try{H.input.focus({preventScroll:!0});return}catch{}try{e.blur()}catch{}}}function yu(){H.bar&&(typeof document>`u`||!document.body||(vu(),_u(!1),H.bar.classList.remove(`show`),H.bar.setAttribute(`aria-hidden`,`true`),H.barEls.forEach(e=>{e.style.height=``,e.style.opacity=``}),H.timerEl&&(H.timerEl.textContent=`00:00`)))}function bu(e){if(!H.barEls.length)return;let t=Math.min(1,Math.sqrt(Math.max(0,e))*6);for(let e=0;e<H.barEls.length-1;e++)H.barEls[e].style.height=H.barEls[e+1].style.height,H.barEls[e].style.opacity=H.barEls[e+1].style.opacity;let n=H.barEls[H.barEls.length-1];n.style.height=`${Math.max(2,Math.round(t*18))}px`,n.style.opacity=t>.06?`1`:`0.35`}function xu(e){H.btn&&(H.btn.classList.toggle(`recording`,e),H.btn.setAttribute(`aria-pressed`,e?`true`:`false`),H.btn.setAttribute(`aria-label`,r(e?`voice.stop`:`voice.start`)),H.btn.title=r(e?`voice.stop`:`voice.start`))}function Su(e){document.body?.classList.toggle(`voice-recording-active`,!!e)}function Cu(){if(H.port)return H.port;try{let e=chrome.runtime.connect({name:`asr`});return e.onMessage.addListener(zu),e.onDisconnect.addListener(()=>{H.port=null,(H.phase===`recording`||H.phase===`finalizing`)&&(Mu(),Nu(),H.draft=null,H.lastText=``,xu(!1),Su(!1),hu(r(`voice.connectionLost`),`warn`),setTimeout(()=>{H.phase===`idle`&&yu()},3500))}),H.port=e,e}catch(e){return i.warn(`[Voice] connect port failed:`,e?.message||e),null}}function wu(e,t){if(bu(t),Tu(t),H.port)try{H.port.postMessage({type:`audio`,data:Ql(e)})}catch(e){i.debug(`[Voice] post audio failed:`,e?.message||e)}}function Tu(e){if(H.phase!==`recording`&&H.phase!==`starting`)return;if(e>=ql){H.silentSince=0,H.silenceWarned&&(H.silenceWarned=!1,hu(r(`voice.listening`)));return}let t=Date.now();if(!H.silentSince){H.silentSince=t;return}H.silenceWarned||t-H.silentSince>=Kl&&(H.silenceWarned=!0,hu(r(`voice.noSpeech`),`warn`))}var Eu=[`voice-capture-worklet.js`,`dist/voice-capture-worklet.js`],Du;async function Ou(){if(Du!==void 0)return Du;for(let e of Eu){let t=``;try{t=chrome.runtime.getURL(e)}catch{continue}try{let e=await fetch(t);if(e&&e.ok)return Du=t,t}catch{}}return Du=null,null}async function ku(e,t){let n=await Ou();if(!n)throw Error(`worklet not found in extension`);await e.audioWorklet.addModule(n);let r=new AudioWorkletNode(e,`voice-capture`),i=Math.abs(e.sampleRate-Gl)>1;r.port.onmessage=t=>{let n=t.data;if(!n||n.type!==`chunk`||!n.pcm)return;let r=new Int16Array(n.pcm);if(i){let t=new Float32Array(r.length);for(let e=0;e<r.length;e++)t[e]=r[e]/32768;r=eu($l(t,e.sampleRate,Gl))}wu(r,n.rms||0)},t.connect(r),H.node=r}function Au(e,t){let n=e.createScriptProcessor(4096,1,1),r=Math.abs(e.sampleRate-Gl)>1;n.onaudioprocess=t=>{let n=t.inputBuffer.getChannelData(0),i=new Float32Array(n);r&&(i=$l(i,e.sampleRate,Gl));let a=0;for(let e=0;e<i.length;e++)a+=i[e]*i[e];wu(eu(i),Math.sqrt(a/Math.max(1,i.length)))},t.connect(n);let i=e.createGain();i.gain.value=0,n.connect(i),i.connect(e.destination),H.mute=i,H.node=n}async function ju(){if(!navigator.mediaDevices?.getUserMedia)throw hu(r(`voice.unsupported`),`warn`),Error(`unsupported`);let e=await at(await tt());H.stream=e.stream,H.deviceFellBack=e.fellBack===!0;let t=window.AudioContext||window.webkitAudioContext,n;try{n=new t({sampleRate:Gl})}catch{n=new t}if(n.state===`suspended`)try{await n.resume()}catch{}H.ctx=n;let a=n.createMediaStreamSource(e.stream);H.source=a;try{await ku(n,a)}catch(e){i.warn(`[Voice] worklet unavailable, fallback to ScriptProcessor:`,e?.message||e),Au(n,a)}}function Mu(){H.timer&&=(clearInterval(H.timer),null);try{H.node?.port?.close?.()}catch{}try{H.node?.disconnect?.()}catch{}try{H.mute?.disconnect?.()}catch{}try{H.source?.disconnect?.()}catch{}try{H.stream?.getTracks?.().forEach(e=>e.stop())}catch{}try{H.ctx?.close?.()}catch{}H.node=null,H.mute=null,H.source=null,H.stream=null,H.ctx=null}function Nu(){H.finishWaitTimer&&=(clearTimeout(H.finishWaitTimer),null),H.phase=`idle`}function Pu(){let e=()=>{let e=Date.now()-H.startedAt;H.timerEl&&(H.timerEl.textContent=Zl(e));let t=H.status;e>=(t&&t.maxRecordingMs||300*1e3)&&Iu(`stop`)};H.timer&&clearInterval(H.timer),H.timer=setInterval(e,200),e()}async function Fu(e={}){if(H.phase!==`idle`||!H.armed&&!e.force&&(await ou(),!H.armed||H.phase!==`idle`))return!1;H.phase=`starting`,H.lastText=``,H.appliedText=``,H.openText=``,H.draft=cu(),H.appliedValue=H.input?H.input.value:``,H.draftSupported=!0,H.silentSince=0,H.silenceWarned=!1,gu(),hu(r(`voice.listening`)),xu(!0),Su(!0);let t=Cu();if(!t)return hu(r(`voice.failed`),`warn`),Nu(),xu(!1),Su(!1),!1;try{await ju()}catch(e){if(H.phase!==`starting`)return Mu(),!1;let n=e?.name||``,i=n===`NotAllowedError`||n===`SecurityError`;i?(hu(r(`voice.micDenied`),`warn`),_u(!0)):hu(r(`voice.failed`),`warn`),Mu(),Nu(),xu(!1),Su(!1);try{t.postMessage({type:`cancel`})}catch{}return setTimeout(()=>{H.phase===`idle`&&yu()},i?12e3:4e3),!1}if(H.phase!==`starting`)return Mu(),!1;H.startedAt=Date.now(),H.phase=`recording`,hu(r(`voice.listening`)),H.deviceFellBack&&(H.deviceFellBack=!1,hu(r(`voice.deviceFallback`),`warn`),setTimeout(()=>{H.phase===`recording`&&hu(r(`voice.listening`))},4e3)),Pu();try{t.postMessage({type:`start`,language:H.status&&H.status.language||`auto`})}catch(e){i.debug(`[Voice] post start failed:`,e?.message||e)}return!0}function Iu(e){if(H.phase!==`recording`)return;H.phase=`finalizing`;let t=Date.now()-H.startedAt;if(Mu(),xu(!1),Su(!1),e===`cancel`){try{H.port?.postMessage({type:`cancel`})}catch{}pu(),Nu(),yu();return}if(t<Jl&&!H.lastText){try{H.port?.postMessage({type:`cancel`})}catch{}pu(),hu(r(`voice.tooShort`),`warn`),Nu(),setTimeout(()=>{H.phase===`idle`&&yu()},2200);return}hu(r(`voice.transcribing`));try{H.port?.postMessage({type:`stop`})}catch{}H.finishWaitTimer&&clearTimeout(H.finishWaitTimer),H.finishWaitTimer=setTimeout(()=>{H.phase===`finalizing`&&Ru(H.lastText,{fallback:!0})},6e4)}function Lu({rollback:e=!0}={}){if(H.phase===`idle`)return!1;let t=H.phase===`recording`||H.phase===`finalizing`;if(H.phase=`finalizing`,Mu(),t)try{H.port?.postMessage({type:`cancel`})}catch{}return e&&pu(),Nu(),xu(!1),Su(!1),yu(),!0}function Ru(e,t={}){let n=Xl(e).trim();if(!n){pu(),hu(r(`voice.noResult`),`warn`),Nu(),setTimeout(()=>{H.phase===`idle`&&yu()},2200);return}if(!H.draft){let e=H.input;if(e){let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length;uu(e.value.slice(0,t)+n+e.value.slice(t),t+n.length)}hu(r(`voice.done`)),Nu(),setTimeout(()=>{H.phase===`idle`&&yu()},1200);return}let a=Array.isArray(t.texts)?t.texts.filter(e=>typeof e==`string`&&e.trim()):[];a.length>1&&!H.draft.items.some(e=>e.id!==null||e.state===`locked`)&&(H.draft.items=a.map((e,t)=>({id:t+1,text:e,state:`refined`}))),H.draft.items.length===0&&(H.draft.items=[{id:null,text:n,state:`refined`}]);let{items:o,changed:s,takeAll:c}=Hl(H.draft.items,n);H.draft.items=o,du(!0),c&&i.debug(`[Voice] final text took over the whole draft`),H.draft=null,H.lastText=``,H.appliedText=``,H.openText=``,Nu(),hu(s>0?r(`voice.refineCorrected`,{n:s}):r(`voice.done`)),setTimeout(()=>{H.phase===`idle`&&yu()},s>0?1800:1200)}function zu(e){if(!(!e||typeof e.type!=`string`)){if(e.type===`ready`){e.draft===!1&&H.phase===`recording`&&i.debug(`[Voice] online model missing, draft disabled`);return}if(e.type===`partial`){if(H.phase!==`recording`&&H.phase!==`finalizing`)return;H.lastText=Xl(e.text),fu(typeof e.open==`string`?e.open:H.lastText);return}if(e.type===`endpoint`)return H.phase!==`recording`&&H.phase,void 0;if(e.type===`sentence`){if(H.phase!==`recording`&&H.phase!==`finalizing`||!H.draft||typeof e.id!=`number`)return;let t=typeof e.refined==`string`&&e.refined?e.refined:null,n=Array.isArray(H.draft.items)?H.draft.items:[],i=n.findIndex(e=>e.id===null),a=n;if(!t&&i>=0){let t=n[i];a=n.map((n,r)=>r===i?t.state===`locked`?{...n,id:e.id}:{id:e.id,text:Xl(e.draft)||n.text,state:`draft`}:n),H.openText=``}if(t&&(a.some(t=>t.id===e.id)?a=Bl(a,{id:e.id,text:t}).map(t=>t.id===e.id&&t.state!==`locked`?{...t,state:`refined`}:t):a.some(e=>e.id===null)||(a=a.concat([{id:e.id,text:t,state:`refined`}]))),a!==n&&(H.draft.items=a,du()),t&&H.phase===`recording`){let e=H.draft.items.filter(e=>e.id!==null&&e.state===`refined`).length;hu(r(`voice.refineListening`,{n:e}))}return}if(e.type===`refine`){e.enabled===!1&&(H.phase===`recording`||H.phase===`finalizing`)&&hu(r(`voice.refineDegraded`),`warn`);return}if(e.type===`final`){if(H.phase!==`recording`&&H.phase!==`finalizing`)return;Ru(e.text||H.lastText,{fallback:e.fallback===!0,texts:e.texts});return}if(e.type===`closed`){H.phase===`finalizing`&&Ru(H.lastText,{fallback:!0});return}if(e.type===`error`){let t=e.code||`internal`;if(t===`max_duration`){H.phase===`recording`&&Iu(`stop`),hu(r(`voice.maxDuration`),`warn`);return}hu(t===`busy`?r(`voice.busy`):t===`model_missing`?`${r(`voice.modelMissing`)} — ${r(`voice.modelMissingHelp`)}`:r(`voice.failed`),`warn`),Mu(),(H.phase===`recording`||H.phase===`finalizing`)&&pu(),Nu(),xu(!1),Su(!1),t===`model_missing`&&ou(),setTimeout(()=>{H.phase===`idle`&&yu()},3500)}}}async function Bu(){return H.phase===`recording`?(Iu(`stop`),!0):H.phase===`starting`||H.phase===`finalizing`?!1:Fu()}function Vu(){return H.phase===`recording`||H.phase===`starting`||H.phase===`finalizing`}function Hu(){return Vu()?Lu({rollback:!0}):!1}function Uu(){return H.phase===`idle`?!1:Lu({rollback:!1})}async function Wu(){try{let e=(await chrome.storage.session?.get?.(`pendingVoiceStart`))?.pendingVoiceStart;return!(!e||(await chrome.storage.session.remove(`pendingVoiceStart`),typeof e!=`number`||Date.now()-e>Wl))}catch{return!1}}function Gu(){if(!H.btn)return;let e=[`Alt+V`];H.shortcutCfg.rightAlt&&e.push(r(`voice.keyRightAlt`)),H.shortcutCfg.rightCtrl&&e.push(r(`voice.keyRightCtrl`));let t=r(`voice.btnTitle`,{keys:e.join(` / `)});H.btn.title=t,H.btn.setAttribute(`aria-label`,t)}async function Ku(){if(H.shortcutCfg=await Ae(),H.shortcutTrigger||=Oe(()=>H.shortcutCfg),Gu(),H.shortcutBound)return;H.shortcutBound=!0,document.addEventListener(`keydown`,e=>{H.shortcutTrigger?.onKeyDown(e)===`cancel`&&e.preventDefault()},!0),document.addEventListener(`keyup`,e=>{H.shortcutTrigger?.onKeyUp(e)===`trigger`&&(!H.armed&&H.phase===`idle`||(e.preventDefault(),Bu()))},!0),window.addEventListener(`blur`,()=>{H.shortcutTrigger?.reset()}),De(e=>{H.shortcutCfg=e,Gu()});let e=async()=>{try{let e=await Ae();if(e.rightAlt===H.shortcutCfg.rightAlt&&e.rightCtrl===H.shortcutCfg.rightCtrl)return;H.shortcutCfg=e,Gu()}catch{}};window.addEventListener(`focus`,()=>{e()}),document.addEventListener(`visibilitychange`,()=>{document.hidden||e()})}async function qu(e={}){if(H.input=document.getElementById(`userInput`),H.btn=document.getElementById(`voiceInputBtn`),H.bar=document.getElementById(`voiceRecorderBar`),H.wave=document.getElementById(`voiceWave`),H.timerEl=document.getElementById(`voiceTimer`),H.statusEl=document.getElementById(`voiceStatusText`),H.permBtn=document.getElementById(`voicePermBtn`),H.adjustInputHeight=typeof e.adjustInputHeight==`function`?e.adjustInputHeight:null,!H.input||!H.btn){i.debug(`[Voice] input or button missing, skip init`);return}mu(),xu(!1),hu(r(`voice.listening`)),await Ku(),H.btn.addEventListener(`click`,e=>{e.preventDefault(),Bu()}),document.getElementById(`voiceCancelBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),Lu({rollback:!0})}),document.getElementById(`voiceDoneBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),Iu(`stop`)}),H.permBtn?.addEventListener(`click`,e=>{e.preventDefault();try{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`asr`}).catch?.(()=>{})}catch{}hu(r(`voice.micDeniedHelp`),`warn`),_u(!1)}),H.input.addEventListener(`input`,()=>{H.programmatic||(H.phase===`recording`||H.phase===`finalizing`)&&su()}),chrome.runtime.onMessage.addListener((e,t,n)=>e?.type===`VOICE_TOGGLE`?(Bu(),n?.({success:!0}),!1):(e?.type===`ASR_STATUS_CHANGED`&&ou(),!1)),window.addEventListener(`pagehide`,()=>{Uu()}),document.addEventListener(`visibilitychange`,()=>{document.hidden&&H.phase===`recording`&&Uu()}),await ou()&&await Wu()&&setTimeout(()=>{Bu()},220)}var Ju=`panel_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8),Yu=new Set,Xu=new Set,Zu=null,Qu=new Map,$u=`queue-context-cleared`,ed=`queue-context-restored`;function td(e){Zu=e}function nd(e){return C.generatingSessionIds.has(e||C.activeSessionId)}function rd(){return{quotedContextText:C.quotedContextText||``,selectedContextText:C.selectedContextText||``,selectedSkills:(C.selectedSkills||[]).slice(),selectedMcpServices:(C.selectedMcpServices||[]).slice(),knowledgeRefs:(C.knowledgeRefs||[]).slice(),selectedPage:C.selectedPage?{...C.selectedPage}:null,attachedImages:(C.attachedImages||[]).slice(),attachedFiles:(C.attachedFiles||[]).slice()}}function id(e){return e?e.attachmentSummary||(e.attachedImages||[]).length||(e.attachedFiles||[]).length?!0:!!(e.quotedContextText&&e.quotedContextText.trim()||e.selectedContextText&&e.selectedContextText.trim()||(e.selectedSkills||[]).length||(e.selectedMcpServices||[]).length||(e.knowledgeRefs||[]).length||e.selectedPage):!1}function ad(){return id(rd())}function od(e){let t=e||{},n=(t.attachedImages||[]).length>0,i=(t.attachedFiles||[]).length>0;return n&&i?r(`sidePanel.defaultPromptAttachments`):n?r(`sidePanel.defaultPromptImage`):i?r(`sidePanel.defaultPromptFile`):(t.knowledgeRefs||[]).length>0?r(`sidePanel.defaultPromptKnowledge`):t.selectedPage?r(`sidePanel.defaultPromptPage`):t.quotedContextText&&t.quotedContextText.trim()||t.selectedContextText&&t.selectedContextText.trim()?r(`sidePanel.defaultPromptSelection`):(t.selectedSkills||[]).length>0||(t.selectedMcpServices||[]).length>0?r(`sidePanel.defaultPromptContext`):``}function sd(){let e=rd();return id(e)&&ld(),e}function cd(e){e&&(e.quotedContextText&&(C.quotedContextText=e.quotedContextText),e.selectedContextText&&(C.selectedContextText=e.selectedContextText),(e.selectedSkills||[]).length&&(C.selectedSkills=e.selectedSkills.slice()),(e.selectedMcpServices||[]).length&&(C.selectedMcpServices=e.selectedMcpServices.slice()),(e.knowledgeRefs||[]).length&&(C.knowledgeRefs=e.knowledgeRefs.slice()),e.selectedPage&&(C.selectedPage={...e.selectedPage}),(e.attachedImages||[]).length&&(C.attachedImages=e.attachedImages.slice()),(e.attachedFiles||[]).length&&(C.attachedFiles=e.attachedFiles.slice()))}function ld(){let e=(C.attachedImages||[]).length>0;if(C.quotedContextText=``,C.selectedContextText=``,C.selectedSkills=[],C.selectedMcpServices=[],C.knowledgeRefs=[],C.selectedPage=null,C.attachedImages=[],C.attachedFiles=[],e){let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}document.dispatchEvent(new CustomEvent($u))}var ud=new Set([`pending`,`extracting`]);function dd(){return(C.attachedFiles||[]).some(e=>ud.has(e&&e.status))}function fd(e){let t=e&&e.attachedImages||[],n=(e&&e.attachedFiles||[]).map(e=>{if(!e||typeof e.dataUrl!=`string`||!e.dataUrl.startsWith(`blob:`))return e;let t={...e};return delete t.dataUrl,t}),r={...e||{}};return delete r.attachedImages,delete r.attachedFiles,r.attachmentSummary=Ur({attachedImages:t,attachedFiles:n}),{light:r,heavy:t.length||n.length?{images:t,files:n}:null}}async function pd(e){if(!e)return{ok:!1,attachments:!1,wantsAttachments:!1};let t=await Gr(e.id)||Qu.get(e.id)||null,n=!!(e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary);return cd({...e.contextSnapshot||{},attachedImages:t&&t.images||[],attachedFiles:t&&t.files||[]}),document.dispatchEvent(new CustomEvent(ed,{detail:{snapshot:e.contextSnapshot||{}}})),{ok:!0,attachments:!!t,wantsAttachments:n}}async function md(e){return e?(Qu.delete(e),Kr(e)):!1}async function hd({autoDrain:e=!0}={}){let t=document.getElementById(`userInput`),n=(t?.value||``).trim()||od(rd());if(!n)return{ok:!1,error:`empty`};Uu();let i=C.activeSessionId;if(!i)return P(r(`queue.noSession`),`error`),{ok:!1,error:`missing_session`};if(dd())return P(r(`queue.filesStillExtracting`),`warning`,4e3),{ok:!1,error:`files_extracting`};let a=sd(),{light:o,heavy:s}=fd(a),c=await vr({sessionId:i,text:n,contextSnapshot:o,hasContext:id(o),attachmentSummary:o.attachmentSummary,source:`manual`});return c.ok?(s&&((await Wr(c.item.id,i,s)).ok||(Qu.set(c.item.id,s),P(r(`queue.attachmentsVolatile`),`warning`,5e3))),t&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus()),P(r(`queue.enqueued`,{position:c.position}),`success`),document.dispatchEvent(new CustomEvent(`queue-enqueued`,{detail:{sessionId:i,item:c.item}})),e&&!nd(i)&&!_r(i)&&_d(i),c):(cd(a),document.dispatchEvent(new CustomEvent(ed,{detail:{snapshot:a}})),c.error===`queue_full`?P(r(`queue.queueFull`,{limit:c.limit}),`warning`):P(r(`queue.enqueueFailed`),`error`),c)}async function gd(e){try{let{list:t}=await ti(),n=(t||[]).find(t=>t.id===e);return n?{messageHistory:Array.isArray(n.messageHistory)?n.messageHistory.slice():[],model:n.model,useTools:n.useTools,enabledTools:Array.isArray(n.enabledTools)?n.enabledTools.slice():n.enabledTools,agentId:n.agentId,temperature:n.temperature,topP:n.topP,contextCompaction:n.contextCompaction,workdir:n.workdir||null,workdirAgentId:n.workdirAgentId||null}:null}catch(e){return i.warn(`[QueueRunner] load session state failed:`,e?.message||e),null}}async function _d(e){let t=e||C.activeSessionId;if(!(!t||!Zu)){if(Yu.has(t)){Xu.add(t);return}Yu.add(t);try{do Xu.delete(t),await vd(t);while(Xu.has(t)&&!_r(t))}finally{Yu.delete(t)}}}async function vd(e){if(nd(e)||_r(e))return;let t=pr(e);if(!t)return;if((t.attempts||0)>=5){await wr(e,t.id,{status:L.FAILED,note:`too_many_attempts`}),P(r(`queue.tooManyAttempts`,{count:5}),`error`,5e3);return}if(!await Ar(e,t.id,Ju)){i.debug(`[QueueRunner] lease held by another panel, skip:`,t.id);return}await xr(e,t.id,L.DISPATCHING,{attempts:(t.attempts||0)+1,lastError:null});let n=await Gr(t.id)||Qu.get(t.id)||null;Qu.delete(t.id);let a=!!t.attachmentSummary&&!n;a&&P(r(`queue.attachmentsMissing`),`warning`,5e3);let o={quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,...t.contextSnapshot||{},attachedImages:n&&n.images||[],attachedFiles:n&&n.files||[]},s=e===C.activeSessionId,c=null;if(!s&&(c=await gd(e),!c)){let t=await jr(e);t&&i.warn(`[QueueRunner] dropped queue of deleted session:`,e,t);return}let l={ok:!0};try{let n={text:t.text,fromQueue:!0,sessionId:e,context:o};s||(n.sessionState=c),l=await Zu(n)||{ok:!0}}catch(e){l={ok:!1,reason:e?.message||`dispatch_error`},i.error(`[QueueRunner] dispatch failed:`,e?.message||e)}hr(e,t.id)?l.ok===!1?l.delivered?(await wr(e,t.id,{status:L.FAILED,note:l.reason||`failed`}),await Kr(t.id)):(await Cr(e,t.id,`dispatch_failed`,l.reason||`dispatch_failed`),Xu.delete(e)):(await wr(e,t.id,{status:L.DONE,note:a?`relayed_no_attachments`:`relayed`}),await Kr(t.id)):i.debug(`[QueueRunner] item removed during dispatch, drop result:`,t.id)}var yd=new Set;function bd(e){let t=e||C.activeSessionId;return t?(yd.add(t),t):null}function xd(e){let t=e||C.activeSessionId;return!!(t&&pr(t))}async function Sd(e){let t=e||C.activeSessionId;t&&(yd.delete(t),await kr(t),await _d(t))}function Cd(e){_r(e)||_d(e)}var wd=new Map,Td=new Set,Ed=new Map,Dd=new Map;function Od(e){let t=e&&e.attachmentSummary;return t?(t.imageCount||0)>0||(t.fileCount||0)>0:!1}function kd(e,t){return`${e}\u0000${t}`}function Ad(e,t){let n=kd(e,t),r=wd.get(n);r&&(clearTimeout(r),wd.delete(n))}async function jd(e,t,n,r){Ad(e,t);let i=hr(e,t);!i||i.status!==L.INJECTING||(await Cr(e,t,n,n),r&&P(r,`warning`,4e3))}function Md(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,r(e))},o=setTimeout(()=>a(null),2e3);try{chrome.runtime.sendMessage({type:`INJECT_MESSAGE`,sessionId:e,itemId:t,text:n},e=>{if(clearTimeout(o),chrome.runtime.lastError){a(null);return}a(e||null)})}catch{clearTimeout(o),a(null)}})}async function Nd(e,t,n={}){let i=t||C.activeSessionId,a=n.auto===!0;if(!i||!e)return{ok:!1,error:`missing_session`};let o=hr(i,e);if(!o)return{ok:!1,error:`not_found`};if(o.status!==L.QUEUED)return{ok:!1,error:`not_queued`};if(Od(o))return a||P(r(`queue.injectNoAttachments`),`warning`,4e3),{ok:!1,error:`has_attachments`};let s=kd(i,e);if(Td.has(s))return{ok:!1,error:`in_flight`};Td.add(s);try{await Sr(i,e),wd.set(s,setTimeout(()=>{jd(i,e,`timeout`,r(`queue.injectTimeout`))},Ln));let t=await Md(i,e,o.text);if(!t)return{ok:!0,pending:!0};if(!t.accepted){let n=t.reason||`rejected`;return await jd(i,e,n,r(n===`no_running_task`?`queue.injectNoTask`:`queue.injectFailed`)),{ok:!1,error:n}}return a?i===C.activeSessionId&&P(r(`queue.autoCarried`,{iteration:n.iteration??`?`}),`success`,2500):P(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0}}finally{Td.delete(s)}}function Pd(e){let t=document.getElementById(`userInput`);t&&t.value.trim()===e&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus())}async function Fd(e){let t=C.activeSessionId,n=String(e||``).trim();if(!t||!n)return{ok:!1,error:`empty`};if(Uu(),!nd(t))return P(r(`queue.injectNoTask`),`warning`,3e3),{ok:!1,error:`no_running_task`};let i=`adhoc_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,7),a=setTimeout(()=>{Ed.has(i)&&(Ed.delete(i),P(r(`queue.injectTimeoutAdhoc`),`warning`,4e3))},Ln);Ed.set(i,{text:n,timer:a});let o=await Md(t,i,n);return o&&!o.accepted?(clearTimeout(a),Ed.delete(i),P(o.reason===`no_running_task`?r(`queue.injectNoTask`):r(`queue.injectFailed`),`warning`,4e3),{ok:!1,error:o.reason}):(o&&o.accepted&&P(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0})}function Id(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=0;for(let r of n){let n=Ed.get(r);if(n){clearTimeout(n.timer),Ed.delete(r),Pd(n.text);continue}Ad(t,r),hr(t,r)&&(i++,wr(t,r,{status:L.INJECTED,note:`injected`,callId:e.callId||null,iteration:e.iteration??null}))}i>0&&t===C.activeSessionId&&P(r(`queue.injected`),`success`,2500),document.dispatchEvent(new CustomEvent(`queue-injected`,{detail:{sessionId:t,items:n,iteration:e.iteration??null}}))}function Ld(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=e.reason||`rejected`,a=r(i===`task_ended`?`queue.injectNoTask`:`queue.injectFailed`);for(let e of n){let r=Ed.get(e);if(r){clearTimeout(r.timer),Ed.delete(e);continue}jd(t,e,i,e===n[0]?a:null)}}function Rd(e){let t=e?.sessionId;if(!t||e.isSubtask===!0||_r(t))return;let n=Pl(e.executionLog);if(!n)return;let r=pr(t),a=r&&!Od(r)?r:null,o=C.chatConfig||{},s=Fl({tracker:Dd.get(t),callId:e.callId||null,iteration:n,everyN:o.queueAutoCarryEveryNIterations,enabled:o.queueAutoCarry!==!1,hasCandidate:!!a});if(Dd.set(t,s.tracker),!s.carry)return;i.debug(`[QueueRunner] auto carry item`,a.id,`at iteration`,n,`session`,t);let c=e.callId||null;Nd(a.id,t,{auto:!0,iteration:n}).then(e=>{!e||e.ok!==!0||Dd.set(t,Il(Dd.get(t),{callId:c}))})}function zd(e){!e||typeof e!=`object`||(e.type===`INJECT_ABSORBED`?Id(e):e.type===`INJECT_REJECTED`?Ld(e):e.type===`EXECUTION_STATUS_UPDATE`&&Rd(e))}async function Bd(){try{if(ar()){i.warn(`[QueueRunner] skip attachment prune in degraded mode`);return}let e=new Set;for(let t of gr())for(let n of lr(t))e.add(n.id);let t=await Jr(e);t&&i.debug(`[QueueRunner] pruned orphan attachments:`,t)}catch(e){i.warn(`[QueueRunner] prune orphan attachments failed:`,e?.message||e)}}var Vd=!1,Hd=null,Ud=[];function Wd(e,t){document.addEventListener(e,t),Ud.push([e,t])}var Gd=1500;function Kd(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,t(e))},i=setTimeout(()=>r(null),Gd);try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`,sessionId:e},e=>{if(clearTimeout(i),chrome.runtime.lastError){r(null);return}r(!!(e&&e.running))})}catch{clearTimeout(i),r(null)}})}async function qd(){if(!C.activeSessionId)return!1;let e=gr();if(e.length===0)return!0;let t=!1;for(let n of e){if(_r(n)||nd(n)||!pr(n))continue;let e=await Kd(n);if(e===null){t=!0;continue}if(!e&&!(_r(n)||nd(n)))return await _d(n),!0}return!t}function Jd(){if(Hd)return;let e=0,t=async()=>{if(Hd=null,++e>25)return;let n=!1;try{n=await qd()}catch(e){i.warn(`[QueueRunner] auto-resume attempt failed:`,e?.message||e)}n||(Hd=setTimeout(t,800))};Hd=setTimeout(t,300)}async function Yd({autoResume:e=!0}={}){Vd||(Vd=!0,await or(),sr(),Bd(),Al(Cd),typeof chrome<`u`&&chrome.runtime?.onMessage?.addListener&&chrome.runtime.onMessage.addListener(zd),Wd(`task-stop-requested`,e=>{let t=e?.detail?.sessionId||C.activeSessionId;if(t){if(yd.delete(t)){kr(t).then(()=>_d(t));return}Or(t,`user_stopped`)}}),Wd(`generating-state-changed`,()=>{let e=C.activeSessionId;if(e){if(C.isGenerating&&_r(e)){kr(e);return}for(let e of gr())if(!(_r(e)||nd(e))&&pr(e)){_d(e);break}}}),Wd(`session-switched`,()=>Jd()),Wd(`visibilitychange`,()=>{document.visibilityState===`visible`&&Jd()}),e&&Jd())}async function Xd(e){let t=e||C.activeSessionId;t&&(await kr(t),await _d(t))}var Zd=[/(?:按|按照|以|用|走|使用|开启|启用|切换?到)\s*(?:goal|目标)\s*模式/i,/(?:进入|改成|改为|设为|设置为|切换到)\s*(?:goal|目标)\s*模式/i,/\b(?:in|use|using|enable|enter|switch\s+to|with)\s+(?:the\s+)?goal\s+mode\b/i,/(?:无人值守|不用管我|别停下来|不要停|直到(?:我|你)(?:叫停|喊停))/,/\bunattended\b|\bwithout\s+(?:me|supervision)\b|\bdon'?t\s+stop\s+until\b/i,/(?:持续|一直|连续)(?:执行|跑|做|干|尝试|迭代)\s*(?:到|直到)/,/(?:跑到|做到|干到|做到)(?:完成|通过|结束|成功)/,/\bkeep\s+(?:working|going|trying|iterating)\s+until\b/i,/\brun\s+until\s+(?:done|complete|passing|it\s+passes)\b/i],Qd=[/直到\s*[^。;;\n]{1,40}?(?:全部|都)?(?:通过|完成|跑通|变绿)/,/(?:确保|保证)\s*[^。;;\n]{1,40}?(?:通过|跑通|可用)/,/\buntil\s+[^.;\n]{1,40}?(?:pass|passes|green|works)\b/i],$d=/(?:不要|不用|不必|无需|取消|关闭|停用|停止|退出|不按|不以|别|不)\s*$/,ef=/\b(?:do\s+not|don'?t|does\s+not|doesn'?t|never|avoid|without|no\s+need\s+to)\s+(?:(?:use|using|enable|enabling|enter|entering|switch(?:ing)?\s+to|turn\s+on|activate|run(?:\s+in)?|go(?:\s+with)?)\s*)?$/i,tf=2e3,nf=40;function rf(e,t,n){let r=[];for(let i of t){let t=i.flags.includes(`g`)?i.flags:`${i.flags}g`,a=new RegExp(i.source,t),o;for(;(o=a.exec(e))!==null&&o[0].length!==0;){let t=e.slice(Math.max(0,o.index-nf),o.index);if(!(n&&($d.test(t)||ef.test(t)))&&(r.push(o[0].trim()),o[0].length===0))break}}return r}function af(e){let t={detected:!1,strength:`none`,matches:[]};if(typeof e!=`string`)return t;let n=e.trim();if(!n)return t;let r=n.slice(0,tf),i=rf(r,Zd,!0);if(i.length>0)return{detected:!0,strength:`strong`,matches:of(i).slice(0,3)};let a=rf(r,Qd,!0);return a.length>0?{detected:!1,strength:`weak`,matches:of(a).slice(0,3)}:t}function of(e){let t=new Set,n=[];for(let r of e){let e=r.toLowerCase();t.has(e)||(t.add(e),n.push(r))}return n}function sf(e){if(typeof e!=`string`)return``;let t=e,n=rf(e.slice(0,tf),Zd,!0);for(let e of n)e&&(t=t.replace(e,` `));return t=t.replace(/^[\s,,。.、::;;-]+/,``).trim(),t||e.trim()}var cf={active:`goal.statusActive`,paused:`goal.statusPaused`,achieved:`goal.statusAchieved`,unmet:`goal.statusUnmet`,budget_limited:`goal.statusBudgetLimited`,cleared:`goal.statusCleared`},lf=new Set([`achieved`,`unmet`,`cleared`]),U=null;function uf(e){return document.getElementById(e)}function df(e){let t=cf[e];return t?r(t):String(e||``)}function ff(e){return!!e&&lf.has(e.status)}function pf(e){return new Promise(t=>{try{chrome.runtime.sendMessage(e,e=>{if(chrome.runtime.lastError){i.debug(`[GoalPanel] message failed:`,chrome.runtime.lastError.message),t(null);return}t(e||null)})}catch(e){i.debug(`[GoalPanel] message threw:`,e?.message),t(null)}})}function mf(e){return pf({type:`SET_GOAL`,...e})}function hf(){if(!U)return;let e=C.goalSnapshot,t=C.goalMode;U.toggle.checked=t;let n=t&&!!e&&(e.status===`paused`||e.status===`budget_limited`);U.group&&(U.group.dataset.goalIdle=n?`1`:``);let i=t||e&&!ff(e);if(U.bar.style.display=i?``:`none`,!i)return;if(U.bar.dataset.status=e?e.status:`none`,U.status.textContent=e?df(e.status):``,U.status.style.display=e?``:`none`,e){U.objective.textContent=e.objective||``,U.objective.title=e.objective||``;let t=M(e,r);n&&e.status===`paused`&&t.push(r(`goal.pausedHintInline`)),U.meta.textContent=t.join(` · `)}else U.objective.textContent=r(`goal.startHint`),U.objective.title=``,U.meta.textContent=``;let a=!!e&&e.status===`active`&&e.autoApprove===!0;U.approve.style.display=a?``:`none`;let o=!!e&&e.status===`active`,s=!!e&&(e.status===`paused`||e.status===`budget_limited`);U.pause.style.display=o?``:`none`,U.resume.style.display=s?``:`none`,U.edit.style.display=e?``:`none`,U.clear.style.display=e?``:`none`}function gf(){return C.activeSessionId||null}async function _f(e=gf()){if(!e)return C.goalSnapshot=null,hf(),null;let t=await pf({type:`GET_GOAL`,sessionId:e});return e===gf()?(C.goalSnapshot=t?.goal||null,hf(),C.goalSnapshot):null}var vf=null;async function yf(){return vf||(vf=await new Promise(e=>{try{chrome.storage.local.get([`goalConfig`],t=>e(t?.goalConfig||{}))}catch(t){i.debug(`[GoalPanel] read goalConfig failed:`,t?.message),e({})}}),vf)}async function bf(){let e=uf(`goalGroup`);if(!e)return;let t=await yf();e.style.display=t.enabled===!1?`none`:``}async function xf({sessionId:e=gf(),text:t=``,attachments:n=[]}={}){if(!e||!String(t||``).trim())return null;let i=await yf(),a=!!C.goalMode;if(i.enabled===!1)return a&&P(r(`goal.disabledHint`),`warning`),null;let o=t;if(!a){if(i.intentDetection===!1)return null;let e=af(t);if(!e.detected)return e.strength===`weak`&&P(r(`goal.intentHint`),`info`,6e3),null;o=String(sf(t)||``).trim()||t}let s=await mf({sessionId:e,action:`set`,objective:o,attachments:Array.isArray(n)?n:[],createdBy:a?`toggle`:`intent`,autoApprove:a});return!s||s.success===!1?(s?.disabled&&P(r(`goal.disabledHint`),`warning`),null):(a||P(r(`goal.intentDetected`),`info`,6e3),e===gf()?(C.goalSnapshot=s.goal||null,hf(),s.goal||null):s.goal||null)}function Sf(e={}){let t=[],n=Array.isArray(e.attachedImages)?e.attachedImages.length:0;n>0&&t.push({kind:`image`,name:r(`goal.attachmentImage`,{count:n})});for(let n of Array.isArray(e.attachedFiles)?e.attachedFiles:[])!n||n.status!==`done`||!n.name||t.push({kind:`file`,name:String(n.name),detail:n.agentPath?`workspace file`:`inline text`});let i=e.selectedPage;i&&(i.title||i.url)&&t.push({kind:`page`,name:String(i.title||i.url),detail:i.id==null?``:`tab ${i.id}`});for(let n of Array.isArray(e.knowledgeRefs)?e.knowledgeRefs:[])n&&n.name&&t.push({kind:`knowledge`,name:String(n.name)});return t}function Cf(){C.goalSnapshot=null,hf()}function wf(){return hf(),_f()}function Tf(e=``){return new Promise(t=>{let n=document.createElement(`div`);n.className=`modal-overlay show`,n.innerHTML=`
|
|
95
95
|
<div class="modal-container" style="min-width:320px;">
|
|
96
|
-
<div class="modal-title">${
|
|
97
|
-
<input type="text" class="goal-edit-input" value="${
|
|
98
|
-
placeholder="${
|
|
96
|
+
<div class="modal-title">${I(r(`goal.editTitle`))}</div>
|
|
97
|
+
<input type="text" class="goal-edit-input" value="${I(e)}"
|
|
98
|
+
placeholder="${I(r(`goal.editPrompt`))}"
|
|
99
99
|
style="width:100%;padding:8px 12px;border:1px solid var(--border-default);border-radius:6px;font-size:14px;margin:8px 0;box-sizing:border-box;">
|
|
100
100
|
<div style="display:flex;justify-content:flex-end;gap:8px;margin-top:12px;">
|
|
101
|
-
<button class="goal-edit-cancel" style="padding:6px 16px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);color:var(--text-secondary);cursor:pointer;">${
|
|
102
|
-
<button class="goal-edit-confirm" style="padding:6px 16px;border:none;border-radius:6px;background:var(--brand-500);color:var(--text-inverse);cursor:pointer;">${
|
|
101
|
+
<button class="goal-edit-cancel" style="padding:6px 16px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);color:var(--text-secondary);cursor:pointer;">${I(r(`common.cancel`))}</button>
|
|
102
|
+
<button class="goal-edit-confirm" style="padding:6px 16px;border:none;border-radius:6px;background:var(--brand-500);color:var(--text-inverse);cursor:pointer;">${I(r(`common.confirm`))}</button>
|
|
103
103
|
</div>
|
|
104
|
-
</div>`,document.body.appendChild(n);let i=n.querySelector(`.goal-edit-input`),a=e=>{n.remove(),t(e)};n.querySelector(`.goal-edit-confirm`).addEventListener(`click`,()=>{a(i.value.trim()||null)}),n.querySelector(`.goal-edit-cancel`).addEventListener(`click`,()=>a(null)),i.addEventListener(`keydown`,e=>{e.key===`Enter`&&a(i.value.trim()||null),e.key===`Escape`&&a(null)}),setTimeout(()=>i.select(),50)})}function Ef(e){!e||e.status===`active`||F(r(`goal.resumeBlocked`,{turns:e.turnBudget}),`warning`,6e3)}function Df(){if(U)return;let e=uf(`goalModeBtn`),t=uf(`goalBar`);if(!e||!t){i.warn(`[GoalPanel] init skipped: DOM not ready`);return}U={toggle:e,group:uf(`goalGroup`),bar:t,status:uf(`goalBarStatus`),objective:uf(`goalBarObjective`),meta:uf(`goalBarMeta`),approve:uf(`goalBarApprove`),edit:uf(`goalBarEditBtn`),pause:uf(`goalBarPauseBtn`),resume:uf(`goalBarResumeBtn`),clear:uf(`goalBarClearBtn`)},U.toggle.checked=!!C.goalMode,U.toggle.addEventListener(`change`,async()=>{if(C.goalMode=U.toggle.checked,hf(),i.debug(`[GoalPanel] goal mode:`,C.goalMode?`enabled`:`disabled`),C.goalMode){let e=gf(),t=C.goalSnapshot;if(e&&t&&(t.status===`paused`||t.status===`budget_limited`)){let t=await mf({sessionId:e,action:`resume`,autoApprove:!0});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf(),Ef(t.goal))}}else{let e=gf();if(e&&!ff(C.goalSnapshot)){let t=await mf({sessionId:e,action:`pause`});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf())}}}),U.edit.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await Tf(C.goalSnapshot?.objective||``);if(!t)return;let n=await mf({sessionId:e,action:`replace`,objective:t,autoApprove:!!C.goalMode});n?.goal&&e===gf()&&(C.goalSnapshot=n.goal,hf(),F(r(`goal.updated`),`success`))}),U.pause.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await mf({sessionId:e,action:`pause`});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf(),t.goal.status===`paused`&&F(r(C.goalMode?`goal.pausedToast`:`goal.pausedToastChipOff`),`info`,6e3))}),U.resume.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await mf({sessionId:e,action:`resume`,autoApprove:!!C.goalMode});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf(),Ef(t.goal))}),U.clear.addEventListener(`click`,async()=>{let e=gf();e&&(!window.showCustomConfirm||await window.showCustomConfirm(r(`goal.clearConfirm`),r(`goal.label`)))&&(await mf({sessionId:e,action:`clear`}),e===gf()&&(C.goalSnapshot=null,hf()))}),U.approve.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await mf({sessionId:e,action:`pause`});C.goalMode=!1,t?.goal&&e===gf()&&(C.goalSnapshot=t.goal),hf(),F(r(`goal.approvalRevoked`),`info`,6e3)}),chrome.runtime.onMessage.addListener(e=>{e?.type===`GOAL_UPDATE`&&(e.sessionId&&e.sessionId!==gf()||(C.goalSnapshot=e.goal||null,hf()))});try{chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!(`goalConfig`in e)||(vf=null,bf())})}catch(e){i.debug(`[GoalPanel] storage.onChanged unavailable:`,e?.message)}bf(),document.addEventListener(`session-switched`,()=>{wf()}),document.addEventListener(`session-hydrated`,()=>{wf()}),document.addEventListener(`session-deleted`,()=>{Cf()}),document.addEventListener(`session-archived`,()=>{Cf()}),hf()}var Of=`combo-collapsed`,kf=`summary-collapsed`,Af=`summary-wrapped`,jf=[Of,kf,Af];function Mf(e){if(!e)return;let t=e.querySelector(`.log-summary`);t&&(t.classList.remove(...jf),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Of),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(kf),!(t.scrollWidth<=t.clientWidth)&&t.classList.add(Af))))}var Nf=null,Pf=0,Ff=!1;function If(e){e&&(Nf=e,Lf(),!Pf&&(Pf=requestAnimationFrame(()=>{Pf=0;let e=Nf;Nf=null,e&&Mf(e)})))}function Lf(){Ff||typeof window>`u`||(Ff=!0,window.addEventListener(`resize`,()=>{let e=document.querySelector(`.execution-log-panel`);e&&If(e)}))}n(`zh`,{execLog:{statusSuccess:`成功`,statusFailed:`失败`,statusProcessing:`处理中`,unknownNode:`未知节点`,sequentialExecution:`顺序执行`,parallelExecution:`并行执行`,subtaskCountStrategy:`{count}个子任务, {strategy}`,messageCountTitle:`本次模型API调用携带的消息数`,toolCountTitle:`本次模型API调用携带的工具定义数`,messageCount:`{count}条`,toolCount:`{count}个`,durationTitle:`耗时`,sectionThought:`💡 思考`,sectionToolCall:`⚡ 工具调用`,labelTool:`工具:`,labelParams:`参数:`,sectionFilterResult:`🔍 筛选结果`,labelSelectedTools:`选中工具:`,labelCount:`数量:`,unitItems:`个`,sectionObservation:`📝 观察结果`,sectionApiRequest:`📡 API 请求`,labelModel:`模型:`,labelTemperature:`温度:`,labelTopP:`top_p:`,labelMessageCount:`消息数:`,labelToolCount:`工具数:`,sectionApiResponse:`📤 API 响应`,labelFinishReason:`完成原因:`,labelFilteredToolCount:`筛选后工具数:`,labelTokenUsage:`Token 使用:`,sectionError:`❌ 错误信息`,sectionSubtaskResult:`✅ 子任务结果`,sectionSubtaskDesc:`📝 任务描述`,subtaskPendingNode:`(待执行)`,sectionReflectionPrompt:`📊 评估提示词`,sectionReflectionRaw:`📤 评估结果(原始响应)`,sectionTokenUsage:`📊 Token 使用`,overallScore:`⭐ 综合评分: {score}/10`,sectionIssues:`📋 发现的问题`,sectionSuggestions:`💡 改进建议`,labelDecision:`🎯 决策: {decision}`,decisionPassed:`✅ 通过`,decisionRevised:`🔧 已修订`,decisionNeedsImprovement:`⚠️ 需改进`,resultUseful:`✅ 结果有用`,resultInvalid:`⚠️ 结果无效`,labelSuggestion:`建议: {suggestion}`,mainTask:`主任务`,stepCount:`({count} 步骤)`,processingDots:`处理中...`,waitingExecution:`等待执行中...`,realtimeLogTitle:`实时执行日志`,executingLabel:`执行中:`,preparing:`准备中...`,totalNodes:`总节点`,labelSuccess:`成功`,labelFailed:`失败`,labelSubtask:`子任务`,expandAll:`展开全部节点`,collapseAll:`收起全部节点`,sectionUserInjection:`💬 插话内容`}}),n(`en`,{execLog:{statusSuccess:`Success`,statusFailed:`Failed`,statusProcessing:`Processing`,unknownNode:`Unknown node`,sequentialExecution:`sequential`,parallelExecution:`parallel`,subtaskCountStrategy:`{count} subtasks, {strategy}`,messageCountTitle:`Number of messages carried in this model API call`,toolCountTitle:`Number of tool definitions carried in this model API call`,messageCount:`{count} msgs`,toolCount:`{count} tools`,durationTitle:`Duration`,sectionThought:`💡 Thought`,sectionToolCall:`⚡ Tool Call`,labelTool:`Tool:`,labelParams:`Params:`,sectionFilterResult:`🔍 Filter Result`,labelSelectedTools:`Selected tools:`,labelCount:`Count:`,unitItems:``,sectionObservation:`📝 Observation`,sectionApiRequest:`📡 API Request`,labelModel:`Model:`,labelTemperature:`Temperature:`,labelTopP:`top_p:`,labelMessageCount:`Messages:`,labelToolCount:`Tools:`,sectionApiResponse:`📤 API Response`,labelFinishReason:`Finish reason:`,labelFilteredToolCount:`Filtered tool count:`,labelTokenUsage:`Token Usage:`,sectionError:`❌ Error`,sectionSubtaskResult:`✅ Subtask Result`,sectionSubtaskDesc:`📝 Task Description`,subtaskPendingNode:`(pending)`,sectionReflectionPrompt:`📊 Reflection Prompt`,sectionReflectionRaw:`📤 Reflection Result (raw)`,sectionTokenUsage:`📊 Token Usage`,overallScore:`⭐ Overall Score: {score}/10`,sectionIssues:`📋 Issues Found`,sectionSuggestions:`💡 Suggestions`,labelDecision:`🎯 Decision: {decision}`,decisionPassed:`✅ Passed`,decisionRevised:`🔧 Revised`,decisionNeedsImprovement:`⚠️ Needs Improvement`,resultUseful:`✅ Useful`,resultInvalid:`⚠️ Invalid`,labelSuggestion:`Suggestion: {suggestion}`,mainTask:`Main Task`,stepCount:`({count} steps)`,processingDots:`Processing...`,waitingExecution:`Waiting for execution...`,realtimeLogTitle:`Real-time Execution Log`,executingLabel:`Executing:`,preparing:`Preparing...`,totalNodes:`Total nodes`,labelSuccess:`Success`,labelFailed:`Failed`,labelSubtask:`Subtask`,expandAll:`Expand all nodes`,collapseAll:`Collapse all nodes`,sectionUserInjection:`💬 Your interjection`}});function Rf(e){if(e?.nodeType!==`tool_exec`||!e?.action)return``;let t=e.action.name||``,n=e.action.params;if(n==null)return``;if(typeof n==`string`&&(n=(()=>{try{return JSON.parse(n)}catch{return{raw:n}}})()),typeof n!=`object`)return String(n).trim();if(t===`execute_command`||t===`agent_exec`)return(n.command||n.cmd||``).toString().trim();if(t===`agent_file`||t===`file_upload`||t===`download_file`){let e=(n.file_path||n.filePath||n.path||n.filename||n.fileName||n.url||``).toString().trim();if(e)return e}if(t===`fetch_url`||t===`interact_element`||t===`fill_form`||t===`manage_tab`||t===`preview_ui`){let e=(n.url||n.href||n.selector||``).toString().trim();if(e)return e}if(t===`search_browser_data`||t===`search_in_page`||t===`exec_log`){let e=(n.query||n.keyword||n.text||``).toString().trim();if(e)return e}if(t===`dispatch_task`){let e=(n.task||``).toString().trim();if(e)return e}if(t===`agent_memory`){let e=(n.action||n.subAction||``).toString().trim();if(e)return e}let r=[`content`,`text`,`prompt`,`description`,`markdown`,`html`,`css`,`js`,`code`,`script`,`data`],i=Object.keys(n).filter(e=>n[e]!=null&&n[e]!==``&&!r.includes(e));if(i.length===0)return``;if(i.length===1){let e=String(n[i[0]]);return`${i[0]}: ${e}`}return i.slice(0,2).map(e=>`${e}=${JSON.stringify(n[e])}`).join(`, `)}function zf(e){return Rf(e)}function Bf(e){let t=Array.isArray(e)?e:[],n=t.filter(e=>e&&e.nodeType===`subtask_plan`&&Array.isArray(e.items));if(n.length===0)return t;let i=t.filter(e=>e&&e.nodeType!==`subtask_plan`),a=new Set(i.filter(e=>e.nodeType===`subtask`&&typeof e.subtaskIndex==`number`).map(e=>e.subtaskIndex)),o=new Map;n.forEach(e=>{e.items.forEach(t=>{!t||typeof t.index!=`number`||o.set(t.index,{item:t,plan:e})})});let s=[];return Array.from(o.keys()).sort((e,t)=>e-t).forEach(e=>{if(a.has(e))return;let{item:t,plan:n}=o.get(e),i=r(`execLog.subtaskPendingNode`);s.push({id:`plan_pending_${n.id||`x`}_${e}`,nodeType:`subtask`,status:`pending`,iteration:0,timestamp:n.timestamp,subtaskIndex:e,subtaskId:t.id,subtaskName:t.name,description:t.description||``,nodeName:t.name?`${t.name} ${i}`:i,taskGroup:`subtask_group_${e}`,taskGroupIndex:e+1,taskGroupName:t.name,isSubtask:!0})}),i.concat(s)}function Vf(e,t){let n=e=>e.status===`pending`?2**53-1:new Date(e.timestamp).getTime();return n(e)-n(t)}function Hf(e){let t=Bf(e).sort(Vf),n=t.length,i=``,a=null;return t.forEach((e,t)=>{let o=e.nodeType===`subtask`,s=e.nodeType===`tool_exec`,c=e.nodeType===`api_call`,l=e.nodeType===`preselect`,u=e.nodeType===`reflection`,d=e.nodeType===`user_injection`,f=s&&e.action?.name===`plan_task`;o&&(a=e.subtaskIndex);let p=``,m=``;d?m=`💬`:u?m=`🎯`:l?m=`🔍`:f?(p=`plan-task-level`,m=`📋`):o?(p=`subtask-level`,m=`🔀`):s&&a!==null?(p=`tool-level`,m=`🔧`):c&&a!==null?(p=`api-level`,m=`📡`):s?m=`⚡`:c&&(m=`📡`);let h=`○`,g=e.status||`processing`;e.status===`success`?h=`✓`:e.status===`failed`&&(h=`✗`),u&&(g=`reflection ${g}`);let _=P(e.nodeName||r(`execLog.unknownNode`));if(e.subtaskIndex!==null&&e.subtaskIndex>=0&&(_=`<span class="subtask-badge">${e.subtaskIndex+1}</span> ${_}`),e.subtaskCount&&(_+=` <span class="plan-badge">(${r(`execLog.subtaskCountStrategy`,{count:e.subtaskCount,strategy:e.strategy===`sequential`?r(`execLog.sequentialExecution`):r(`execLog.parallelExecution`)})})</span>`),(c||l||u)&&e.apiRequest){let t=[];e.apiRequest.messageCount!==void 0&&e.apiRequest.messageCount!==null&&t.push(`💬<span title="${r(`execLog.messageCountTitle`)}">${r(`execLog.messageCount`,{count:e.apiRequest.messageCount})}</span>`),!l&&e.apiRequest.toolCount!==void 0&&e.apiRequest.toolCount!==null&&t.push(`🔧<span title="${r(`execLog.toolCountTitle`)}">${r(`execLog.toolCount`,{count:e.apiRequest.toolCount})}</span>`),t.length>0&&(_+=` <span class="api-info-badge">(${t.join(` `)})</span>`)}if(s){let t=zf(e);t&&(_+=` <span class="node-cmd-preview" title="${nt(t)}">${P(t)}</span>`)}i+=`
|
|
104
|
+
</div>`,document.body.appendChild(n);let i=n.querySelector(`.goal-edit-input`),a=e=>{n.remove(),t(e)};n.querySelector(`.goal-edit-confirm`).addEventListener(`click`,()=>{a(i.value.trim()||null)}),n.querySelector(`.goal-edit-cancel`).addEventListener(`click`,()=>a(null)),i.addEventListener(`keydown`,e=>{e.key===`Enter`&&a(i.value.trim()||null),e.key===`Escape`&&a(null)}),setTimeout(()=>i.select(),50)})}function Ef(e){!e||e.status===`active`||P(r(`goal.resumeBlocked`,{turns:e.turnBudget}),`warning`,6e3)}function Df(){if(U)return;let e=uf(`goalModeBtn`),t=uf(`goalBar`);if(!e||!t){i.warn(`[GoalPanel] init skipped: DOM not ready`);return}U={toggle:e,group:uf(`goalGroup`),bar:t,status:uf(`goalBarStatus`),objective:uf(`goalBarObjective`),meta:uf(`goalBarMeta`),approve:uf(`goalBarApprove`),edit:uf(`goalBarEditBtn`),pause:uf(`goalBarPauseBtn`),resume:uf(`goalBarResumeBtn`),clear:uf(`goalBarClearBtn`)},U.toggle.checked=!!C.goalMode,U.toggle.addEventListener(`change`,async()=>{if(C.goalMode=U.toggle.checked,hf(),i.debug(`[GoalPanel] goal mode:`,C.goalMode?`enabled`:`disabled`),C.goalMode){let e=gf(),t=C.goalSnapshot;if(e&&t&&(t.status===`paused`||t.status===`budget_limited`)){let t=await mf({sessionId:e,action:`resume`,autoApprove:!0});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf(),Ef(t.goal))}}else{let e=gf();if(e&&!ff(C.goalSnapshot)){let t=await mf({sessionId:e,action:`pause`});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf())}}}),U.edit.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await Tf(C.goalSnapshot?.objective||``);if(!t)return;let n=await mf({sessionId:e,action:`replace`,objective:t,autoApprove:!!C.goalMode});n?.goal&&e===gf()&&(C.goalSnapshot=n.goal,hf(),P(r(`goal.updated`),`success`))}),U.pause.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await mf({sessionId:e,action:`pause`});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf(),t.goal.status===`paused`&&P(r(C.goalMode?`goal.pausedToast`:`goal.pausedToastChipOff`),`info`,6e3))}),U.resume.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await mf({sessionId:e,action:`resume`,autoApprove:!!C.goalMode});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf(),Ef(t.goal))}),U.clear.addEventListener(`click`,async()=>{let e=gf();e&&(!window.showCustomConfirm||await window.showCustomConfirm(r(`goal.clearConfirm`),r(`goal.label`)))&&(await mf({sessionId:e,action:`clear`}),e===gf()&&(C.goalSnapshot=null,hf()))}),U.approve.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await mf({sessionId:e,action:`pause`});C.goalMode=!1,t?.goal&&e===gf()&&(C.goalSnapshot=t.goal),hf(),P(r(`goal.approvalRevoked`),`info`,6e3)}),chrome.runtime.onMessage.addListener(e=>{e?.type===`GOAL_UPDATE`&&(e.sessionId&&e.sessionId!==gf()||(C.goalSnapshot=e.goal||null,hf()))});try{chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!(`goalConfig`in e)||(vf=null,bf())})}catch(e){i.debug(`[GoalPanel] storage.onChanged unavailable:`,e?.message)}bf(),document.addEventListener(`session-switched`,()=>{wf()}),document.addEventListener(`session-hydrated`,()=>{wf()}),document.addEventListener(`session-deleted`,()=>{Cf()}),document.addEventListener(`session-archived`,()=>{Cf()}),hf()}var Of=`combo-collapsed`,kf=`summary-collapsed`,Af=`summary-wrapped`,jf=[Of,kf,Af];function Mf(e){if(!e)return;let t=e.querySelector(`.log-summary`);t&&(t.classList.remove(...jf),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Of),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(kf),!(t.scrollWidth<=t.clientWidth)&&t.classList.add(Af))))}var Nf=null,Pf=0,Ff=!1;function If(e){e&&(Nf=e,Lf(),!Pf&&(Pf=requestAnimationFrame(()=>{Pf=0;let e=Nf;Nf=null,e&&Mf(e)})))}function Lf(){Ff||typeof window>`u`||(Ff=!0,window.addEventListener(`resize`,()=>{let e=document.querySelector(`.execution-log-panel`);e&&If(e)}))}n(`zh`,{execLog:{statusSuccess:`成功`,statusFailed:`失败`,statusProcessing:`处理中`,unknownNode:`未知节点`,sequentialExecution:`顺序执行`,parallelExecution:`并行执行`,subtaskCountStrategy:`{count}个子任务, {strategy}`,messageCountTitle:`本次模型API调用携带的消息数`,toolCountTitle:`本次模型API调用携带的工具定义数`,messageCount:`{count}条`,toolCount:`{count}个`,durationTitle:`耗时`,sectionThought:`💡 思考`,sectionToolCall:`⚡ 工具调用`,labelTool:`工具:`,labelParams:`参数:`,sectionFilterResult:`🔍 筛选结果`,labelSelectedTools:`选中工具:`,labelCount:`数量:`,unitItems:`个`,sectionObservation:`📝 观察结果`,sectionApiRequest:`📡 API 请求`,labelModel:`模型:`,labelTemperature:`温度:`,labelTopP:`top_p:`,labelMessageCount:`消息数:`,labelToolCount:`工具数:`,sectionApiResponse:`📤 API 响应`,labelFinishReason:`完成原因:`,labelFilteredToolCount:`筛选后工具数:`,labelTokenUsage:`Token 使用:`,sectionError:`❌ 错误信息`,sectionSubtaskResult:`✅ 子任务结果`,sectionSubtaskDesc:`📝 任务描述`,subtaskPendingNode:`(待执行)`,sectionReflectionPrompt:`📊 评估提示词`,sectionReflectionRaw:`📤 评估结果(原始响应)`,sectionTokenUsage:`📊 Token 使用`,overallScore:`⭐ 综合评分: {score}/10`,sectionIssues:`📋 发现的问题`,sectionSuggestions:`💡 改进建议`,labelDecision:`🎯 决策: {decision}`,decisionPassed:`✅ 通过`,decisionRevised:`🔧 已修订`,decisionNeedsImprovement:`⚠️ 需改进`,resultUseful:`✅ 结果有用`,resultInvalid:`⚠️ 结果无效`,labelSuggestion:`建议: {suggestion}`,mainTask:`主任务`,stepCount:`({count} 步骤)`,processingDots:`处理中...`,waitingExecution:`等待执行中...`,realtimeLogTitle:`实时执行日志`,executingLabel:`执行中:`,preparing:`准备中...`,totalNodes:`总节点`,labelSuccess:`成功`,labelFailed:`失败`,labelSubtask:`子任务`,expandAll:`展开全部节点`,collapseAll:`收起全部节点`,sectionUserInjection:`💬 插话内容`}}),n(`en`,{execLog:{statusSuccess:`Success`,statusFailed:`Failed`,statusProcessing:`Processing`,unknownNode:`Unknown node`,sequentialExecution:`sequential`,parallelExecution:`parallel`,subtaskCountStrategy:`{count} subtasks, {strategy}`,messageCountTitle:`Number of messages carried in this model API call`,toolCountTitle:`Number of tool definitions carried in this model API call`,messageCount:`{count} msgs`,toolCount:`{count} tools`,durationTitle:`Duration`,sectionThought:`💡 Thought`,sectionToolCall:`⚡ Tool Call`,labelTool:`Tool:`,labelParams:`Params:`,sectionFilterResult:`🔍 Filter Result`,labelSelectedTools:`Selected tools:`,labelCount:`Count:`,unitItems:``,sectionObservation:`📝 Observation`,sectionApiRequest:`📡 API Request`,labelModel:`Model:`,labelTemperature:`Temperature:`,labelTopP:`top_p:`,labelMessageCount:`Messages:`,labelToolCount:`Tools:`,sectionApiResponse:`📤 API Response`,labelFinishReason:`Finish reason:`,labelFilteredToolCount:`Filtered tool count:`,labelTokenUsage:`Token Usage:`,sectionError:`❌ Error`,sectionSubtaskResult:`✅ Subtask Result`,sectionSubtaskDesc:`📝 Task Description`,subtaskPendingNode:`(pending)`,sectionReflectionPrompt:`📊 Reflection Prompt`,sectionReflectionRaw:`📤 Reflection Result (raw)`,sectionTokenUsage:`📊 Token Usage`,overallScore:`⭐ Overall Score: {score}/10`,sectionIssues:`📋 Issues Found`,sectionSuggestions:`💡 Suggestions`,labelDecision:`🎯 Decision: {decision}`,decisionPassed:`✅ Passed`,decisionRevised:`🔧 Revised`,decisionNeedsImprovement:`⚠️ Needs Improvement`,resultUseful:`✅ Useful`,resultInvalid:`⚠️ Invalid`,labelSuggestion:`Suggestion: {suggestion}`,mainTask:`Main Task`,stepCount:`({count} steps)`,processingDots:`Processing...`,waitingExecution:`Waiting for execution...`,realtimeLogTitle:`Real-time Execution Log`,executingLabel:`Executing:`,preparing:`Preparing...`,totalNodes:`Total nodes`,labelSuccess:`Success`,labelFailed:`Failed`,labelSubtask:`Subtask`,expandAll:`Expand all nodes`,collapseAll:`Collapse all nodes`,sectionUserInjection:`💬 Your interjection`}});function Rf(e){if(e?.nodeType!==`tool_exec`||!e?.action)return``;let t=e.action.name||``,n=e.action.params;if(n==null)return``;if(typeof n==`string`&&(n=(()=>{try{return JSON.parse(n)}catch{return{raw:n}}})()),typeof n!=`object`)return String(n).trim();if(t===`execute_command`||t===`agent_exec`)return(n.command||n.cmd||``).toString().trim();if(t===`agent_file`||t===`file_upload`||t===`download_file`){let e=(n.file_path||n.filePath||n.path||n.filename||n.fileName||n.url||``).toString().trim();if(e)return e}if(t===`fetch_url`||t===`interact_element`||t===`fill_form`||t===`manage_tab`||t===`preview_ui`){let e=(n.url||n.href||n.selector||``).toString().trim();if(e)return e}if(t===`search_browser_data`||t===`search_in_page`||t===`exec_log`){let e=(n.query||n.keyword||n.text||``).toString().trim();if(e)return e}if(t===`dispatch_task`){let e=(n.task||``).toString().trim();if(e)return e}if(t===`agent_memory`){let e=(n.action||n.subAction||``).toString().trim();if(e)return e}let r=[`content`,`text`,`prompt`,`description`,`markdown`,`html`,`css`,`js`,`code`,`script`,`data`],i=Object.keys(n).filter(e=>n[e]!=null&&n[e]!==``&&!r.includes(e));if(i.length===0)return``;if(i.length===1){let e=String(n[i[0]]);return`${i[0]}: ${e}`}return i.slice(0,2).map(e=>`${e}=${JSON.stringify(n[e])}`).join(`, `)}function zf(e){return Rf(e)}function Bf(e){let t=Array.isArray(e)?e:[],n=t.filter(e=>e&&e.nodeType===`subtask_plan`&&Array.isArray(e.items));if(n.length===0)return t;let i=t.filter(e=>e&&e.nodeType!==`subtask_plan`),a=new Set(i.filter(e=>e.nodeType===`subtask`&&typeof e.subtaskIndex==`number`).map(e=>e.subtaskIndex)),o=new Map;n.forEach(e=>{e.items.forEach(t=>{!t||typeof t.index!=`number`||o.set(t.index,{item:t,plan:e})})});let s=[];return Array.from(o.keys()).sort((e,t)=>e-t).forEach(e=>{if(a.has(e))return;let{item:t,plan:n}=o.get(e),i=r(`execLog.subtaskPendingNode`);s.push({id:`plan_pending_${n.id||`x`}_${e}`,nodeType:`subtask`,status:`pending`,iteration:0,timestamp:n.timestamp,subtaskIndex:e,subtaskId:t.id,subtaskName:t.name,description:t.description||``,nodeName:t.name?`${t.name} ${i}`:i,taskGroup:`subtask_group_${e}`,taskGroupIndex:e+1,taskGroupName:t.name,isSubtask:!0})}),i.concat(s)}function Vf(e,t){let n=e=>e.status===`pending`?2**53-1:new Date(e.timestamp).getTime();return n(e)-n(t)}function Hf(e){let t=Bf(e).sort(Vf),n=t.length,i=``,a=null;return t.forEach((e,t)=>{let o=e.nodeType===`subtask`,s=e.nodeType===`tool_exec`,c=e.nodeType===`api_call`,l=e.nodeType===`preselect`,u=e.nodeType===`reflection`,d=e.nodeType===`user_injection`,f=s&&e.action?.name===`plan_task`;o&&(a=e.subtaskIndex);let p=``,m=``;d?m=`💬`:u?m=`🎯`:l?m=`🔍`:f?(p=`plan-task-level`,m=`📋`):o?(p=`subtask-level`,m=`🔀`):s&&a!==null?(p=`tool-level`,m=`🔧`):c&&a!==null?(p=`api-level`,m=`📡`):s?m=`⚡`:c&&(m=`📡`);let h=`○`,g=e.status||`processing`;e.status===`success`?h=`✓`:e.status===`failed`&&(h=`✗`),u&&(g=`reflection ${g}`);let _=I(e.nodeName||r(`execLog.unknownNode`));if(e.subtaskIndex!==null&&e.subtaskIndex>=0&&(_=`<span class="subtask-badge">${e.subtaskIndex+1}</span> ${_}`),e.subtaskCount&&(_+=` <span class="plan-badge">(${r(`execLog.subtaskCountStrategy`,{count:e.subtaskCount,strategy:e.strategy===`sequential`?r(`execLog.sequentialExecution`):r(`execLog.parallelExecution`)})})</span>`),(c||l||u)&&e.apiRequest){let t=[];e.apiRequest.messageCount!==void 0&&e.apiRequest.messageCount!==null&&t.push(`💬<span title="${r(`execLog.messageCountTitle`)}">${r(`execLog.messageCount`,{count:e.apiRequest.messageCount})}</span>`),!l&&e.apiRequest.toolCount!==void 0&&e.apiRequest.toolCount!==null&&t.push(`🔧<span title="${r(`execLog.toolCountTitle`)}">${r(`execLog.toolCount`,{count:e.apiRequest.toolCount})}</span>`),t.length>0&&(_+=` <span class="api-info-badge">(${t.join(` `)})</span>`)}if(s){let t=zf(e);t&&(_+=` <span class="node-cmd-preview" title="${Me(t)}">${I(t)}</span>`)}i+=`
|
|
105
105
|
<div class="timeline-item ${p}" data-status="${e.status||`processing`}" data-node-type="${e.nodeType||``}">
|
|
106
106
|
<div class="timeline-line"></div>
|
|
107
107
|
<div class="timeline-dot ${g}">
|
|
@@ -112,22 +112,22 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
112
112
|
<span class="expand-icon">▼</span>
|
|
113
113
|
<span class="node-icon">${m}</span>
|
|
114
114
|
<span class="iteration-badge">[${t+1}/${n}]</span>
|
|
115
|
-
<span class="node-name" title="${
|
|
116
|
-
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${
|
|
115
|
+
<span class="node-name" title="${I(e.nodeName||r(`execLog.unknownNode`))}">${_}</span>
|
|
116
|
+
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${Be(e.duration||0)}</span>
|
|
117
117
|
</div>
|
|
118
118
|
|
|
119
119
|
<div class="timeline-details">
|
|
120
120
|
${d&&e.content?`
|
|
121
121
|
<div class="timeline-section">
|
|
122
122
|
<div class="section-title">${r(`execLog.sectionUserInjection`)}</div>
|
|
123
|
-
<div class="section-content">${
|
|
123
|
+
<div class="section-content">${I(e.content)}</div>
|
|
124
124
|
</div>
|
|
125
125
|
`:``}
|
|
126
126
|
|
|
127
127
|
${e.thought&&e.thought.trim()?`
|
|
128
128
|
<div class="timeline-section">
|
|
129
129
|
<div class="section-title">${r(`execLog.sectionThought`)}</div>
|
|
130
|
-
<div class="section-content">${
|
|
130
|
+
<div class="section-content">${I(e.thought)}</div>
|
|
131
131
|
</div>
|
|
132
132
|
`:``}
|
|
133
133
|
|
|
@@ -135,8 +135,8 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
135
135
|
<div class="timeline-section">
|
|
136
136
|
<div class="section-title">${r(`execLog.sectionToolCall`)}</div>
|
|
137
137
|
<div class="section-content">
|
|
138
|
-
<strong>${r(`execLog.labelTool`)}</strong> ${
|
|
139
|
-
<strong>${r(`execLog.labelParams`)}</strong> <code>${
|
|
138
|
+
<strong>${r(`execLog.labelTool`)}</strong> ${I(e.action.name)}<br>
|
|
139
|
+
<strong>${r(`execLog.labelParams`)}</strong> <code>${I(JSON.stringify(e.action.params,null,2))}</code>
|
|
140
140
|
</div>
|
|
141
141
|
</div>
|
|
142
142
|
`:``}
|
|
@@ -145,7 +145,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
145
145
|
<div class="timeline-section">
|
|
146
146
|
<div class="section-title">${r(`execLog.sectionFilterResult`)}</div>
|
|
147
147
|
<div class="section-content">
|
|
148
|
-
<strong>${r(`execLog.labelSelectedTools`)}</strong> ${e.action.params.selected.map(e=>
|
|
148
|
+
<strong>${r(`execLog.labelSelectedTools`)}</strong> ${e.action.params.selected.map(e=>I(e)).join(`, `)}<br>
|
|
149
149
|
<strong>${r(`execLog.labelCount`)}</strong> ${e.action.params.selected.length} ${r(`execLog.unitItems`)}
|
|
150
150
|
</div>
|
|
151
151
|
</div>
|
|
@@ -154,7 +154,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
154
154
|
${e.observation?`
|
|
155
155
|
<div class="timeline-section">
|
|
156
156
|
<div class="section-title">${r(`execLog.sectionObservation`)}</div>
|
|
157
|
-
<div class="section-content">${
|
|
157
|
+
<div class="section-content">${I(e.observation)}</div>
|
|
158
158
|
</div>
|
|
159
159
|
`:``}
|
|
160
160
|
|
|
@@ -162,7 +162,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
162
162
|
<div class="timeline-section">
|
|
163
163
|
<div class="section-title">${r(`execLog.sectionApiRequest`)}</div>
|
|
164
164
|
<div class="section-content">
|
|
165
|
-
${e.apiRequest.model?`<strong>${r(`execLog.labelModel`)}</strong> ${
|
|
165
|
+
${e.apiRequest.model?`<strong>${r(`execLog.labelModel`)}</strong> ${I(e.apiRequest.model)}<br>`:``}
|
|
166
166
|
${e.apiRequest.temperature===void 0?``:`<strong>${r(`execLog.labelTemperature`)}</strong> ${e.apiRequest.temperature}<br>`}
|
|
167
167
|
${e.apiRequest.top_p===void 0?``:`<strong>top_p:</strong> ${e.apiRequest.top_p}<br>`}
|
|
168
168
|
${e.apiRequest.messageCount===void 0?``:`<strong>${r(`execLog.labelMessageCount`)}</strong> ${e.apiRequest.messageCount}<br>`}
|
|
@@ -175,7 +175,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
175
175
|
<div class="timeline-section">
|
|
176
176
|
<div class="section-title">${r(`execLog.sectionApiResponse`)}</div>
|
|
177
177
|
<div class="section-content">
|
|
178
|
-
${e.apiResponse.finishReason?`<strong>${r(`execLog.labelFinishReason`)}</strong> ${
|
|
178
|
+
${e.apiResponse.finishReason?`<strong>${r(`execLog.labelFinishReason`)}</strong> ${I(e.apiResponse.finishReason)}<br>`:``}
|
|
179
179
|
${e.apiResponse.toolCountAfter===void 0?``:`<strong>${r(`execLog.labelFilteredToolCount`)}</strong> ${e.apiResponse.toolCountAfter} ${r(`execLog.unitItems`)}<br>`}
|
|
180
180
|
${e.apiResponse.tokenUsage?`
|
|
181
181
|
<strong>${r(`execLog.labelTokenUsage`)}</strong><br>
|
|
@@ -190,21 +190,21 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
190
190
|
${e.error?`
|
|
191
191
|
<div class="timeline-section error">
|
|
192
192
|
<div class="section-title">${r(`execLog.sectionError`)}</div>
|
|
193
|
-
<div class="section-content">${
|
|
193
|
+
<div class="section-content">${I(e.error)}</div>
|
|
194
194
|
</div>
|
|
195
195
|
`:``}
|
|
196
196
|
|
|
197
197
|
${e.description?`
|
|
198
198
|
<div class="timeline-section">
|
|
199
199
|
<div class="section-title">${r(`execLog.sectionSubtaskDesc`)}</div>
|
|
200
|
-
<div class="section-content">${
|
|
200
|
+
<div class="section-content">${I(e.description)}</div>
|
|
201
201
|
</div>
|
|
202
202
|
`:``}
|
|
203
203
|
|
|
204
204
|
${e.result?`
|
|
205
205
|
<div class="timeline-section">
|
|
206
206
|
<div class="section-title">${r(`execLog.sectionSubtaskResult`)}</div>
|
|
207
|
-
<div class="section-content">${
|
|
207
|
+
<div class="section-content">${I(e.result)}</div>
|
|
208
208
|
</div>
|
|
209
209
|
`:``}
|
|
210
210
|
|
|
@@ -213,13 +213,13 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
213
213
|
${e.prompt?`
|
|
214
214
|
<div class="timeline-section">
|
|
215
215
|
<div class="section-title">${r(`execLog.sectionReflectionPrompt`)}</div>
|
|
216
|
-
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:300px;overflow-y:auto;">${
|
|
216
|
+
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:300px;overflow-y:auto;">${I(e.prompt)}</pre></div>
|
|
217
217
|
</div>
|
|
218
218
|
`:``}
|
|
219
219
|
${e.rawContent?`
|
|
220
220
|
<div class="timeline-section">
|
|
221
221
|
<div class="section-title">${r(`execLog.sectionReflectionRaw`)}</div>
|
|
222
|
-
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto;">${
|
|
222
|
+
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto;">${I(e.rawContent)}</pre></div>
|
|
223
223
|
</div>
|
|
224
224
|
`:``}
|
|
225
225
|
${e.apiResponse?.tokenUsage?`
|
|
@@ -248,19 +248,19 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
248
248
|
`:``}
|
|
249
249
|
${e.issues&&e.issues.length>0?`
|
|
250
250
|
<div class="section-title">${r(`execLog.sectionIssues`)}</div>
|
|
251
|
-
<div class="section-content"><ul>${e.issues.map(e=>`<li>${
|
|
251
|
+
<div class="section-content"><ul>${e.issues.map(e=>`<li>${I(e)}</li>`).join(``)}</ul></div>
|
|
252
252
|
`:``}
|
|
253
253
|
${e.suggestions&&e.suggestions.length>0?`
|
|
254
254
|
<div class="section-title">${r(`execLog.sectionSuggestions`)}</div>
|
|
255
|
-
<div class="section-content"><ul>${e.suggestions.map(e=>`<li>${
|
|
255
|
+
<div class="section-content"><ul>${e.suggestions.map(e=>`<li>${I(e)}</li>`).join(``)}</ul></div>
|
|
256
256
|
`:``}
|
|
257
257
|
${e.action?.decision?`
|
|
258
|
-
<div class="section-title">${r(`execLog.labelDecision`,{decision:
|
|
258
|
+
<div class="section-title">${r(`execLog.labelDecision`,{decision:I(e.action.decision===`passed`?r(`execLog.decisionPassed`):e.action.decision===`revised`?r(`execLog.decisionRevised`):e.action.decision===`needs_improvement`?r(`execLog.decisionNeedsImprovement`):e.action.decision)})}</div>
|
|
259
259
|
`:``}
|
|
260
260
|
${e.useful===void 0?``:`
|
|
261
261
|
<div class="section-title">${e.useful?r(`execLog.resultUseful`):r(`execLog.resultInvalid`)}</div>
|
|
262
|
-
${e.reasoning?`<div class="section-content">${
|
|
263
|
-
${e.suggestion?`<div class="section-content">${r(`execLog.labelSuggestion`,{suggestion:
|
|
262
|
+
${e.reasoning?`<div class="section-content">${I(e.reasoning)}</div>`:``}
|
|
263
|
+
${e.suggestion?`<div class="section-content">${r(`execLog.labelSuggestion`,{suggestion:I(e.suggestion)})}</div>`:``}
|
|
264
264
|
`}
|
|
265
265
|
</div>
|
|
266
266
|
`:``}
|
|
@@ -279,7 +279,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
279
279
|
<span class="task-group-expand-icon">▼</span>
|
|
280
280
|
<span class="task-group-icon">📁</span>
|
|
281
281
|
<span class="task-group-index">${e.groupIndex}</span>
|
|
282
|
-
<span class="task-group-name">${
|
|
282
|
+
<span class="task-group-name">${I(e.groupName)}</span>
|
|
283
283
|
<span class="task-group-count">${r(`execLog.stepCount`,{count:e.entries.length})}</span>
|
|
284
284
|
</div>
|
|
285
285
|
</div>
|
|
@@ -307,7 +307,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
307
307
|
`,e.forEach((e,r)=>{n+=Kf(e,r,t)}),n+=`
|
|
308
308
|
</div>
|
|
309
309
|
</div>
|
|
310
|
-
`,n}function Gf(e,t){let n=``;return e.forEach((e,r)=>{n+=Kf(e,r,t)}),n}function Kf(e,t,n){let i=e.nodeType===`subtask`,a=e.nodeType===`tool_exec`,o=e.nodeType===`api_call`,s=e.nodeType===`preselect`,c=e.nodeType===`reflection`,l=e.nodeType===`user_injection`,u=a&&e.action?.name===`plan_task`,d=``,f=``;l?f=`💬`:c?(d=`reflection-level`,f=`🎯`):s?f=`📡`:u?(d=`plan-task-level`,f=`📋`):i?(d=`subtask-level`,f=`🔀`):a?(d=`tool-level`,f=`🔧`):o?(d=`api-level`,f=`📡`):a?f=`⚡`:o&&(f=`📡`);let p=`○`,m=e.status||`processing`;e.status===`success`?p=`✓`:e.status===`failed`&&(p=`✗`),c&&(m=`reflection ${m}`);let h=
|
|
310
|
+
`,n}function Gf(e,t){let n=``;return e.forEach((e,r)=>{n+=Kf(e,r,t)}),n}function Kf(e,t,n){let i=e.nodeType===`subtask`,a=e.nodeType===`tool_exec`,o=e.nodeType===`api_call`,s=e.nodeType===`preselect`,c=e.nodeType===`reflection`,l=e.nodeType===`user_injection`,u=a&&e.action?.name===`plan_task`,d=``,f=``;l?f=`💬`:c?(d=`reflection-level`,f=`🎯`):s?f=`📡`:u?(d=`plan-task-level`,f=`📋`):i?(d=`subtask-level`,f=`🔀`):a?(d=`tool-level`,f=`🔧`):o?(d=`api-level`,f=`📡`):a?f=`⚡`:o&&(f=`📡`);let p=`○`,m=e.status||`processing`;e.status===`success`?p=`✓`:e.status===`failed`&&(p=`✗`),c&&(m=`reflection ${m}`);let h=I(e.nodeName||r(`execLog.unknownNode`));if(e.subtaskCount&&(h+=` <span class="plan-badge">(${r(`execLog.subtaskCountStrategy`,{count:e.subtaskCount,strategy:e.strategy===`sequential`?r(`execLog.sequentialExecution`):r(`execLog.parallelExecution`)})})</span>`),(o||s)&&e.apiRequest){let t=[];e.apiRequest.messageCount!==void 0&&e.apiRequest.messageCount!==null&&t.push(`💬<span title="${r(`execLog.messageCountTitle`)}">${r(`execLog.messageCount`,{count:e.apiRequest.messageCount})}</span>`),!s&&e.apiRequest.toolCount!==void 0&&e.apiRequest.toolCount!==null&&t.push(`🔧<span title="${r(`execLog.toolCountTitle`)}">${r(`execLog.toolCount`,{count:e.apiRequest.toolCount})}</span>`),t.length>0&&(h+=` <span class="api-info-badge">(${t.join(` `)})</span>`)}if(a){let t=zf(e);t&&(h+=` <span class="node-cmd-preview" title="${Me(t)}">${I(t)}</span>`)}return`
|
|
311
311
|
<div class="timeline-item ${d}">
|
|
312
312
|
<div class="timeline-line"></div>
|
|
313
313
|
<div class="timeline-dot ${m}">
|
|
@@ -318,22 +318,22 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
318
318
|
<span class="expand-icon">▼</span>
|
|
319
319
|
<span class="node-icon">${f}</span>
|
|
320
320
|
<span class="iteration-badge">[${t+1}/${n}]</span>
|
|
321
|
-
<span class="node-name" title="${
|
|
322
|
-
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${
|
|
321
|
+
<span class="node-name" title="${I(e.nodeName||r(`execLog.unknownNode`))}">${h}</span>
|
|
322
|
+
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${Be(e.duration)}</span>
|
|
323
323
|
</div>
|
|
324
324
|
|
|
325
325
|
<div class="timeline-details">
|
|
326
326
|
${l&&e.content?`
|
|
327
327
|
<div class="timeline-section">
|
|
328
328
|
<div class="section-title">${r(`execLog.sectionUserInjection`)}</div>
|
|
329
|
-
<div class="section-content">${
|
|
329
|
+
<div class="section-content">${I(e.content)}</div>
|
|
330
330
|
</div>
|
|
331
331
|
`:``}
|
|
332
332
|
|
|
333
333
|
${e.thought&&e.thought.trim()?`
|
|
334
334
|
<div class="timeline-section">
|
|
335
335
|
<div class="section-title">${r(`execLog.sectionThought`)}</div>
|
|
336
|
-
<div class="section-content">${
|
|
336
|
+
<div class="section-content">${I(e.thought)}</div>
|
|
337
337
|
</div>
|
|
338
338
|
`:``}
|
|
339
339
|
|
|
@@ -341,8 +341,8 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
341
341
|
<div class="timeline-section">
|
|
342
342
|
<div class="section-title">${r(`execLog.sectionToolCall`)}</div>
|
|
343
343
|
<div class="section-content">
|
|
344
|
-
<strong>${r(`execLog.labelTool`)}</strong> ${
|
|
345
|
-
<strong>${r(`execLog.labelParams`)}</strong> <code>${
|
|
344
|
+
<strong>${r(`execLog.labelTool`)}</strong> ${I(e.action.name)}<br>
|
|
345
|
+
<strong>${r(`execLog.labelParams`)}</strong> <code>${I(JSON.stringify(e.action.params,null,2))}</code>
|
|
346
346
|
</div>
|
|
347
347
|
</div>
|
|
348
348
|
`:``}
|
|
@@ -351,7 +351,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
351
351
|
<div class="timeline-section">
|
|
352
352
|
<div class="section-title">${r(`execLog.sectionFilterResult`)}</div>
|
|
353
353
|
<div class="section-content">
|
|
354
|
-
<strong>${r(`execLog.labelSelectedTools`)}</strong> ${e.action.params.selected.map(e=>
|
|
354
|
+
<strong>${r(`execLog.labelSelectedTools`)}</strong> ${e.action.params.selected.map(e=>I(e)).join(`, `)}<br>
|
|
355
355
|
<strong>${r(`execLog.labelCount`)}</strong> ${e.action.params.selected.length} ${r(`execLog.unitItems`)}
|
|
356
356
|
</div>
|
|
357
357
|
</div>
|
|
@@ -360,7 +360,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
360
360
|
${e.observation&&e.observation!==e.error?`
|
|
361
361
|
<div class="timeline-section">
|
|
362
362
|
<div class="section-title">${r(`execLog.sectionObservation`)}</div>
|
|
363
|
-
<div class="section-content">${
|
|
363
|
+
<div class="section-content">${I(e.observation)}</div>
|
|
364
364
|
</div>
|
|
365
365
|
`:``}
|
|
366
366
|
|
|
@@ -368,7 +368,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
368
368
|
<div class="timeline-section">
|
|
369
369
|
<div class="section-title">${r(`execLog.sectionApiRequest`)}</div>
|
|
370
370
|
<div class="section-content">
|
|
371
|
-
${e.apiRequest.model?`<strong>${r(`execLog.labelModel`)}</strong> ${
|
|
371
|
+
${e.apiRequest.model?`<strong>${r(`execLog.labelModel`)}</strong> ${I(e.apiRequest.model)}<br>`:``}
|
|
372
372
|
${e.apiRequest.temperature===void 0?``:`<strong>${r(`execLog.labelTemperature`)}</strong> ${e.apiRequest.temperature}<br>`}
|
|
373
373
|
${e.apiRequest.top_p===void 0?``:`<strong>top_p:</strong> ${e.apiRequest.top_p}<br>`}
|
|
374
374
|
${e.apiRequest.messageCount===void 0?``:`<strong>${r(`execLog.labelMessageCount`)}</strong> ${e.apiRequest.messageCount}<br>`}
|
|
@@ -381,7 +381,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
381
381
|
<div class="timeline-section">
|
|
382
382
|
<div class="section-title">${r(`execLog.sectionApiResponse`)}</div>
|
|
383
383
|
<div class="section-content">
|
|
384
|
-
${e.apiResponse.finishReason?`<strong>${r(`execLog.labelFinishReason`)}</strong> ${
|
|
384
|
+
${e.apiResponse.finishReason?`<strong>${r(`execLog.labelFinishReason`)}</strong> ${I(e.apiResponse.finishReason)}<br>`:``}
|
|
385
385
|
${e.apiResponse.toolCountAfter===void 0?``:`<strong>${r(`execLog.labelFilteredToolCount`)}</strong> ${e.apiResponse.toolCountAfter} ${r(`execLog.unitItems`)}<br>`}
|
|
386
386
|
${e.apiResponse.tokenUsage?`
|
|
387
387
|
<strong>${r(`execLog.labelTokenUsage`)}</strong><br>
|
|
@@ -396,21 +396,21 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
396
396
|
${e.error?`
|
|
397
397
|
<div class="timeline-section error">
|
|
398
398
|
<div class="section-title">${r(`execLog.sectionError`)}</div>
|
|
399
|
-
<div class="section-content">${
|
|
399
|
+
<div class="section-content">${I(e.error)}</div>
|
|
400
400
|
</div>
|
|
401
401
|
`:``}
|
|
402
402
|
|
|
403
403
|
${e.description?`
|
|
404
404
|
<div class="timeline-section">
|
|
405
405
|
<div class="section-title">${r(`execLog.sectionSubtaskDesc`)}</div>
|
|
406
|
-
<div class="section-content">${
|
|
406
|
+
<div class="section-content">${I(e.description)}</div>
|
|
407
407
|
</div>
|
|
408
408
|
`:``}
|
|
409
409
|
|
|
410
410
|
${e.result?`
|
|
411
411
|
<div class="timeline-section">
|
|
412
412
|
<div class="section-title">${r(`execLog.sectionSubtaskResult`)}</div>
|
|
413
|
-
<div class="section-content">${
|
|
413
|
+
<div class="section-content">${I(e.result)}</div>
|
|
414
414
|
</div>
|
|
415
415
|
`:``}
|
|
416
416
|
|
|
@@ -432,26 +432,26 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
432
432
|
`:``}
|
|
433
433
|
${e.issues&&e.issues.length>0?`
|
|
434
434
|
<div class="section-title">${r(`execLog.sectionIssues`)}</div>
|
|
435
|
-
<div class="section-content"><ul>${e.issues.map(e=>`<li>${
|
|
435
|
+
<div class="section-content"><ul>${e.issues.map(e=>`<li>${I(e)}</li>`).join(``)}</ul></div>
|
|
436
436
|
`:``}
|
|
437
437
|
${e.suggestions&&e.suggestions.length>0?`
|
|
438
438
|
<div class="section-title">${r(`execLog.sectionSuggestions`)}</div>
|
|
439
|
-
<div class="section-content"><ul>${e.suggestions.map(e=>`<li>${
|
|
439
|
+
<div class="section-content"><ul>${e.suggestions.map(e=>`<li>${I(e)}</li>`).join(``)}</ul></div>
|
|
440
440
|
`:``}
|
|
441
441
|
${e.action?.decision?`
|
|
442
|
-
<div class="section-title">${r(`execLog.labelDecision`,{decision:
|
|
442
|
+
<div class="section-title">${r(`execLog.labelDecision`,{decision:I(e.action.decision===`passed`?r(`execLog.decisionPassed`):e.action.decision===`revised`?r(`execLog.decisionRevised`):e.action.decision===`needs_improvement`?r(`execLog.decisionNeedsImprovement`):e.action.decision)})}</div>
|
|
443
443
|
`:``}
|
|
444
444
|
${e.useful===void 0?``:`
|
|
445
445
|
<div class="section-title">${e.useful?r(`execLog.resultUseful`):r(`execLog.resultInvalid`)}</div>
|
|
446
|
-
${e.reasoning?`<div class="section-content">${
|
|
447
|
-
${e.suggestion?`<div class="section-content">${r(`execLog.labelSuggestion`,{suggestion:
|
|
446
|
+
${e.reasoning?`<div class="section-content">${I(e.reasoning)}</div>`:``}
|
|
447
|
+
${e.suggestion?`<div class="section-content">${r(`execLog.labelSuggestion`,{suggestion:I(e.suggestion)})}</div>`:``}
|
|
448
448
|
`}
|
|
449
449
|
</div>
|
|
450
450
|
`:``}
|
|
451
451
|
</div>
|
|
452
452
|
</div>
|
|
453
453
|
</div>
|
|
454
|
-
`}function qf(e){let t=``,n=null;return e.forEach((i,a)=>{let o=i.nodeType===`subtask`,s=i.nodeType===`tool_exec`,c=i.nodeType===`api_call`,l=i.nodeType===`preselect`,u=i.nodeType===`reflection`,d=i.nodeType===`user_injection`,f=s&&i.action?.name===`plan_task`;o&&(n=i.subtaskIndex);let p=``,m=``;d?m=`💬`:u?m=`🎯`:l?m=`🔍`:f?(p=`plan-task-level`,m=`📋`):o?(p=`subtask-level`,m=`🔀`):s&&n!==null?(p=`tool-level`,m=`🔧`):c&&n!==null?(p=`api-level`,m=`📡`):s?m=`⚡`:c&&(m=`📡`);let h=`○`,g=i.status||`processing`;i.status===`success`?h=`✓`:i.status===`failed`&&(h=`✗`);let _=
|
|
454
|
+
`}function qf(e){let t=``,n=null;return e.forEach((i,a)=>{let o=i.nodeType===`subtask`,s=i.nodeType===`tool_exec`,c=i.nodeType===`api_call`,l=i.nodeType===`preselect`,u=i.nodeType===`reflection`,d=i.nodeType===`user_injection`,f=s&&i.action?.name===`plan_task`;o&&(n=i.subtaskIndex);let p=``,m=``;d?m=`💬`:u?m=`🎯`:l?m=`🔍`:f?(p=`plan-task-level`,m=`📋`):o?(p=`subtask-level`,m=`🔀`):s&&n!==null?(p=`tool-level`,m=`🔧`):c&&n!==null?(p=`api-level`,m=`📡`):s?m=`⚡`:c&&(m=`📡`);let h=`○`,g=i.status||`processing`;i.status===`success`?h=`✓`:i.status===`failed`&&(h=`✗`);let _=I(i.nodeName||r(`execLog.unknownNode`));if(i.subtaskId&&(_=`<span class="subtask-badge">${n===null?``:n+1}</span> ${_}`),i.subtaskCount&&(_+=` <span class="plan-badge">(${r(`execLog.subtaskCountStrategy`,{count:i.subtaskCount,strategy:i.strategy===`sequential`?r(`execLog.sequentialExecution`):r(`execLog.parallelExecution`)})})</span>`),(c||l||u)&&i.apiRequest){let e=[];i.apiRequest.messageCount!==void 0&&i.apiRequest.messageCount!==null&&e.push(`💬<span title="${r(`execLog.messageCountTitle`)}">${r(`execLog.messageCount`,{count:i.apiRequest.messageCount})}</span>`),!l&&i.apiRequest.toolCount!==void 0&&i.apiRequest.toolCount!==null&&e.push(`🔧<span title="${r(`execLog.toolCountTitle`)}">${r(`execLog.toolCount`,{count:i.apiRequest.toolCount})}</span>`),e.length>0&&(_+=` <span class="api-info-badge">(${e.join(` `)})</span>`)}if(s){let e=zf(i);e&&(_+=` <span class="node-cmd-preview" title="${Me(e)}">${I(e)}</span>`)}t+=`
|
|
455
455
|
<div class="timeline-item ${p}">
|
|
456
456
|
<div class="timeline-line"></div>
|
|
457
457
|
<div class="timeline-dot ${g}">
|
|
@@ -462,22 +462,22 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
462
462
|
<span class="expand-icon">▼</span>
|
|
463
463
|
<span class="node-icon">${m}</span>
|
|
464
464
|
<span class="iteration-badge">[${a+1}/${e.length}]</span>
|
|
465
|
-
<span class="node-name" title="${
|
|
466
|
-
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${
|
|
465
|
+
<span class="node-name" title="${I(i.nodeName||r(`execLog.unknownNode`))}">${_}</span>
|
|
466
|
+
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${Be(i.duration)}</span>
|
|
467
467
|
</div>
|
|
468
468
|
|
|
469
469
|
<div class="timeline-details">
|
|
470
470
|
${d&&i.content?`
|
|
471
471
|
<div class="timeline-section">
|
|
472
472
|
<div class="section-title">${r(`execLog.sectionUserInjection`)}</div>
|
|
473
|
-
<div class="section-content">${
|
|
473
|
+
<div class="section-content">${I(i.content)}</div>
|
|
474
474
|
</div>
|
|
475
475
|
`:``}
|
|
476
476
|
|
|
477
477
|
${i.thought&&i.thought.trim()?`
|
|
478
478
|
<div class="timeline-section">
|
|
479
479
|
<div class="section-title">${r(`execLog.sectionThought`)}</div>
|
|
480
|
-
<div class="section-content">${
|
|
480
|
+
<div class="section-content">${I(i.thought)}</div>
|
|
481
481
|
</div>
|
|
482
482
|
`:``}
|
|
483
483
|
|
|
@@ -485,8 +485,8 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
485
485
|
<div class="timeline-section">
|
|
486
486
|
<div class="section-title">${r(`execLog.sectionToolCall`)}</div>
|
|
487
487
|
<div class="section-content">
|
|
488
|
-
<strong>${r(`execLog.labelTool`)}</strong> ${
|
|
489
|
-
<strong>${r(`execLog.labelParams`)}</strong> <code>${
|
|
488
|
+
<strong>${r(`execLog.labelTool`)}</strong> ${I(i.action.name)}<br>
|
|
489
|
+
<strong>${r(`execLog.labelParams`)}</strong> <code>${I(JSON.stringify(i.action.params,null,2))}</code>
|
|
490
490
|
</div>
|
|
491
491
|
</div>
|
|
492
492
|
`:``}
|
|
@@ -495,7 +495,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
495
495
|
<div class="timeline-section">
|
|
496
496
|
<div class="section-title">${r(`execLog.sectionFilterResult`)}</div>
|
|
497
497
|
<div class="section-content">
|
|
498
|
-
<strong>${r(`execLog.labelSelectedTools`)}</strong> ${i.action.params.selected.map(e=>
|
|
498
|
+
<strong>${r(`execLog.labelSelectedTools`)}</strong> ${i.action.params.selected.map(e=>I(e)).join(`, `)}<br>
|
|
499
499
|
<strong>${r(`execLog.labelCount`)}</strong> ${i.action.params.selected.length} ${r(`execLog.unitItems`)}
|
|
500
500
|
</div>
|
|
501
501
|
</div>
|
|
@@ -504,7 +504,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
504
504
|
${i.observation?`
|
|
505
505
|
<div class="timeline-section">
|
|
506
506
|
<div class="section-title">${r(`execLog.sectionObservation`)}</div>
|
|
507
|
-
<div class="section-content">${
|
|
507
|
+
<div class="section-content">${I(i.observation)}</div>
|
|
508
508
|
</div>
|
|
509
509
|
`:``}
|
|
510
510
|
|
|
@@ -512,7 +512,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
512
512
|
<div class="timeline-section">
|
|
513
513
|
<div class="section-title">${r(`execLog.sectionApiRequest`)}</div>
|
|
514
514
|
<div class="section-content">
|
|
515
|
-
${i.apiRequest.model?`<strong>${r(`execLog.labelModel`)}</strong> ${
|
|
515
|
+
${i.apiRequest.model?`<strong>${r(`execLog.labelModel`)}</strong> ${I(i.apiRequest.model)}<br>`:``}
|
|
516
516
|
${i.apiRequest.temperature===void 0?``:`<strong>${r(`execLog.labelTemperature`)}</strong> ${i.apiRequest.temperature}<br>`}
|
|
517
517
|
${i.apiRequest.top_p===void 0?``:`<strong>top_p:</strong> ${i.apiRequest.top_p}<br>`}
|
|
518
518
|
${i.apiRequest.messageCount===void 0?``:`<strong>${r(`execLog.labelMessageCount`)}</strong> ${i.apiRequest.messageCount}<br>`}
|
|
@@ -525,7 +525,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
525
525
|
<div class="timeline-section">
|
|
526
526
|
<div class="section-title">${r(`execLog.sectionApiResponse`)}</div>
|
|
527
527
|
<div class="section-content">
|
|
528
|
-
${i.apiResponse.finishReason?`<strong>${r(`execLog.labelFinishReason`)}</strong> ${
|
|
528
|
+
${i.apiResponse.finishReason?`<strong>${r(`execLog.labelFinishReason`)}</strong> ${I(i.apiResponse.finishReason)}<br>`:``}
|
|
529
529
|
${i.apiResponse.toolCountAfter===void 0?``:`<strong>${r(`execLog.labelFilteredToolCount`)}</strong> ${i.apiResponse.toolCountAfter} ${r(`execLog.unitItems`)}<br>`}
|
|
530
530
|
${i.apiResponse.tokenUsage?`
|
|
531
531
|
<strong>${r(`execLog.labelTokenUsage`)}</strong><br>
|
|
@@ -540,21 +540,21 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
540
540
|
${i.error?`
|
|
541
541
|
<div class="timeline-section error">
|
|
542
542
|
<div class="section-title">${r(`execLog.sectionError`)}</div>
|
|
543
|
-
<div class="section-content">${
|
|
543
|
+
<div class="section-content">${I(i.error)}</div>
|
|
544
544
|
</div>
|
|
545
545
|
`:``}
|
|
546
546
|
|
|
547
547
|
${i.description?`
|
|
548
548
|
<div class="timeline-section">
|
|
549
549
|
<div class="section-title">${r(`execLog.sectionSubtaskDesc`)}</div>
|
|
550
|
-
<div class="section-content">${
|
|
550
|
+
<div class="section-content">${I(i.description)}</div>
|
|
551
551
|
</div>
|
|
552
552
|
`:``}
|
|
553
553
|
|
|
554
554
|
${i.result?`
|
|
555
555
|
<div class="timeline-section">
|
|
556
556
|
<div class="section-title">${r(`execLog.sectionSubtaskResult`)}</div>
|
|
557
|
-
<div class="section-content">${
|
|
557
|
+
<div class="section-content">${I(i.result)}</div>
|
|
558
558
|
</div>
|
|
559
559
|
`:``}
|
|
560
560
|
|
|
@@ -563,13 +563,13 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
563
563
|
${i.prompt?`
|
|
564
564
|
<div class="timeline-section">
|
|
565
565
|
<div class="section-title">${r(`execLog.sectionReflectionPrompt`)}</div>
|
|
566
|
-
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:300px;overflow-y:auto;">${
|
|
566
|
+
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:300px;overflow-y:auto;">${I(i.prompt)}</pre></div>
|
|
567
567
|
</div>
|
|
568
568
|
`:``}
|
|
569
569
|
${i.rawContent?`
|
|
570
570
|
<div class="timeline-section">
|
|
571
571
|
<div class="section-title">${r(`execLog.sectionReflectionRaw`)}</div>
|
|
572
|
-
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto;">${
|
|
572
|
+
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto;">${I(i.rawContent)}</pre></div>
|
|
573
573
|
</div>
|
|
574
574
|
`:``}
|
|
575
575
|
${i.apiResponse?.tokenUsage?`
|
|
@@ -598,19 +598,19 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
598
598
|
`:``}
|
|
599
599
|
${i.issues&&i.issues.length>0?`
|
|
600
600
|
<div class="section-title">${r(`execLog.sectionIssues`)}</div>
|
|
601
|
-
<div class="section-content"><ul>${i.issues.map(e=>`<li>${
|
|
601
|
+
<div class="section-content"><ul>${i.issues.map(e=>`<li>${I(e)}</li>`).join(``)}</ul></div>
|
|
602
602
|
`:``}
|
|
603
603
|
${i.suggestions&&i.suggestions.length>0?`
|
|
604
604
|
<div class="section-title">${r(`execLog.sectionSuggestions`)}</div>
|
|
605
|
-
<div class="section-content"><ul>${i.suggestions.map(e=>`<li>${
|
|
605
|
+
<div class="section-content"><ul>${i.suggestions.map(e=>`<li>${I(e)}</li>`).join(``)}</ul></div>
|
|
606
606
|
`:``}
|
|
607
607
|
${i.action?.decision?`
|
|
608
|
-
<div class="section-title">${r(`execLog.labelDecision`,{decision:
|
|
608
|
+
<div class="section-title">${r(`execLog.labelDecision`,{decision:I(i.action.decision===`passed`?r(`execLog.decisionPassed`):i.action.decision===`revised`?r(`execLog.decisionRevised`):i.action.decision===`needs_improvement`?r(`execLog.decisionNeedsImprovement`):i.action.decision)})}</div>
|
|
609
609
|
`:``}
|
|
610
610
|
${i.useful===void 0?``:`
|
|
611
611
|
<div class="section-title">${i.useful?r(`execLog.resultUseful`):r(`execLog.resultInvalid`)}</div>
|
|
612
|
-
${i.reasoning?`<div class="section-content">${
|
|
613
|
-
${i.suggestion?`<div class="section-content">${r(`execLog.labelSuggestion`,{suggestion:
|
|
612
|
+
${i.reasoning?`<div class="section-content">${I(i.reasoning)}</div>`:``}
|
|
613
|
+
${i.suggestion?`<div class="section-content">${r(`execLog.labelSuggestion`,{suggestion:I(i.suggestion)})}</div>`:``}
|
|
614
614
|
`}
|
|
615
615
|
</div>
|
|
616
616
|
`:``}
|
|
@@ -683,10 +683,10 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
683
683
|
<div class="export-session-item" data-id="${e.id}">
|
|
684
684
|
<input type="checkbox" class="export-session-checkbox" data-session-id="${e.id}" ${n?`checked`:``}>
|
|
685
685
|
<div class="export-session-info">
|
|
686
|
-
<div class="export-session-title">${
|
|
686
|
+
<div class="export-session-title">${I(e.title||r(`exportImport.unnamedSession`))}${n?`<span class="current-badge">${r(`exportImport.currentBadge`)}</span>`:``}</div>
|
|
687
687
|
<div class="export-session-meta">${r(`exportImport.messageCount`,{count:a})}${o?` · `+o:``}</div>
|
|
688
688
|
</div>
|
|
689
|
-
</div>`}).join(``),t.querySelectorAll(`.export-session-item`).forEach(e=>{let t=e.querySelector(`.export-session-checkbox`);e.addEventListener(`click`,e=>{e.target!==t&&(t.checked=!t.checked),ep()})});let a=document.getElementById(`exportSelectAllBtn`),o=document.getElementById(`exportDeselectAllBtn`),s=document.getElementById(`exportSelectCurrentBtn`);a&&(a.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=!0}),ep()}),o&&(o.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=!1}),ep()}),s&&(s.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=e.dataset.sessionId===i}),ep()}),ep()}}catch(e){i.error(`[SidePanel] loadsession column table failed:`,e),t.innerHTML=`<div class="export-sessions-empty">${r(`exportImport.loadFailed`)}</div>`}e.classList.add(`show`)}}function ep(){document.querySelectorAll(`#exportSessionsList .export-session-checkbox`);let e=document.querySelectorAll(`#exportSessionsList .export-session-checkbox:checked`),t=document.getElementById(`exportSelectedCount`);t&&(t.textContent=r(`chatExport.selectedCount`,{count:e.length}));let n=document.getElementById(`exportSessionsOkBtn`);n&&(n.textContent=r(`exportImport.exportSelectedCount`,{count:e.length}),n.disabled=e.length===0,n.style.opacity=e.length===0?`0.5`:`1`)}function tp(){let e=document.getElementById(`exportSessionsModal`);e&&e.classList.remove(`show`)}async function np(){let e=document.querySelectorAll(`#exportSessionsList .export-session-checkbox:checked`),t=Array.from(e).map(e=>e.dataset.sessionId);if(t.length===0){F(r(`exportImport.selectAtLeastOne`),`warning`);return}try{let{list:e}=await ti({withActiveHistory:!1}),n=await Promise.all(e.filter(e=>t.includes(e.id)).map(async e=>await w(e.id)||e)),a={version:1,exportedAt:new Date().toISOString(),sessions:n.map(e=>({title:e.title||r(`exportImport.unnamedSession`),model:e.model,useTools:e.useTools,enabledTools:e.enabledTools,temperature:e.temperature,topP:e.topP,createdAt:e.createdAt,messageHistory:(e.messageHistory||[]).map(e=>({role:e.role,content:e.content||``,executionLog:e.executionLog||[],htmlContent:e.htmlContent||``,reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,messageId:e.messageId||``,timestamp:e.timestamp||``}))}))},o=new Date,s=o.getFullYear()+String(o.getMonth()+1).padStart(2,`0`)+String(o.getDate()).padStart(2,`0`)+`-`+String(o.getHours()).padStart(2,`0`)+String(o.getMinutes()).padStart(2,`0`)+String(o.getSeconds()).padStart(2,`0`),c=n.length,l=c===1?`ai-helper-${n[0].title.replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)}-${s}.aihelper.json`:`ai-helper-${c}sessions-${s}.aihelper.json`,u=JSON.stringify(a,null,2),d=new Blob([u],{type:`application/json;charset=utf-8;`}),f=URL.createObjectURL(d),p=document.createElement(`a`);p.href=f,p.download=l,document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(f),tp(),i.debug(`[SidePanel] sessionexported:`,l,`total `,c,`session`),F(r(`exportImport.exportSuccess`,{count:c}),`success`)}catch(e){i.error(`[SidePanel] export failed:`,e),F(r(`exportImport.exportFailed`,{message:e.message}),`error`)}}function rp(){let e=document.getElementById(`exportSessionsCloseBtn`),t=document.getElementById(`exportSessionsCancelBtn`),n=document.getElementById(`exportSessionsOkBtn`),r=document.getElementById(`exportSessionsModal`);e&&e.addEventListener(`click`,tp),t&&t.addEventListener(`click`,tp),n&&n.addEventListener(`click`,np),r&&r.addEventListener(`click`,e=>{e.target===r&&tp()})}function ip(){let e=document.getElementById(`importSessionsFile`);e&&(e.value=``,e.click())}async function ap(e){try{let t=await e.text(),n=JSON.parse(t),a=[];if(n.version&&n.sessions&&Array.isArray(n.sessions))a=n.sessions;else if(Array.isArray(n))a=n.length>0&&n[0].role?[{title:r(`exportImport.importedConversation`),messageHistory:n.map(e=>({role:e.role||`user`,content:e.content||``}))}]:(n.length>0&&n[0].title,n);else throw Error(r(`exportImport.unrecognizedFormat`));if(a.length===0){F(r(`exportImport.noImportableData`),`warning`);return}let o=await gi(a);await yo(),i.debug(`[SidePanel] import complete:`,o.length,`session`),F(r(`exportImport.importSuccess`,{count:o.length}),`success`)}catch(e){i.error(`[SidePanel] import failed:`,e),F(r(`exportImport.importFailed`,{message:e.message}),`error`)}}n(`zh`,{imagePreview:{clickToEnlarge:`点击查看大图`,removeImage:`移除图片`}}),n(`en`,{imagePreview:{clickToEnlarge:`Click to enlarge`,removeImage:`Remove image`}});var op=1,sp=0,cp=0,lp=!1,up=0,dp=0,fp=0,pp=0,mp=[],hp=0,gp=!1,_p=`brush`,vp=`#ff4757`,yp=4,bp=1,xp=!1,Sp=0,Cp=0,wp=0,Tp=0,Ep=0,Dp=0,Op=[],W=null,G=null,K=null,q=null;function kp(e){let t=document.createElement(`a`);t.href=e,t.download=`image_${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.jpg`,document.body.appendChild(t),t.click(),document.body.removeChild(t)}function Ap(){let e=document.getElementById(`imagePreviewLarge`);e&&(e.style.transform=`translate(${sp}px, ${cp}px) scale(${op})`,op>1?(e.classList.add(`zoomable`),lp?e.classList.add(`dragging`):e.classList.remove(`dragging`)):e.classList.remove(`zoomable`,`dragging`))}function jp(){op=1,sp=0,cp=0,lp=!1,Ap()}function Mp(e,t){let n=document.getElementById(`imagePreviewOverlay`),r=document.getElementById(`imagePreviewLarge`),i=document.getElementById(`imagePreviewEdit`);if(!n||!r)return;let a=t&&t.closest(`.user-message-images`);i&&(i.style.display=a?`none`:``),Np(e,t),Pp(),Ip(e),n.classList.add(`show`)}function Np(e,t){mp=[],t&&(t.closest(`.image-preview-bar`)||t.classList.contains(`image-preview-thumb`)?document.querySelectorAll(`.image-preview-thumb`).forEach(e=>{e.src&&mp.push(e.src)}):t.closest(`.user-message-images`)&&t.closest(`.user-message-images`).querySelectorAll(`.user-message-image`).forEach(e=>{e.src&&mp.push(e.src)})),mp.length===0&&document.querySelectorAll(`.image-preview-thumb, .user-message-image`).forEach(e=>{e.src&&mp.push(e.src)}),hp=mp.indexOf(e),hp===-1&&(mp.push(e),hp=mp.length-1)}function Pp(){let e=document.getElementById(`imagePreviewPrev`),t=document.getElementById(`imagePreviewNext`),n=document.getElementById(`imagePreviewCounter`);mp.length<=1?(e&&(e.style.display=`none`),t&&(t.style.display=`none`),n&&(n.style.display=`none`)):(e&&(e.style.display=``),t&&(t.style.display=``),n&&(n.style.display=``),Fp())}function Fp(){let e=document.getElementById(`imagePreviewPrev`),t=document.getElementById(`imagePreviewNext`),n=document.getElementById(`imagePreviewCounter`);e&&(e.disabled=!1),t&&(t.disabled=!1),n&&(n.textContent=`${hp+1} / ${mp.length}`)}function Ip(e){let t=document.getElementById(`imagePreviewLarge`);t&&(jp(),t.src=e)}function Lp(e){let t=mp.length;t!==0&&(hp=(hp+e+t)%t,Ip(mp[hp]),Fp())}function Rp(){let e=document.getElementById(`imagePreviewOverlay`);if(!e||e.dataset.initialized)return;e.dataset.initialized=`true`;let t=document.getElementById(`imagePreviewLarge`),n=()=>{e.classList.remove(`show`),jp()},r=e.querySelector(`.image-preview-close`);r&&r.addEventListener(`click`,n);let i=document.getElementById(`imagePreviewDownload`);i&&i.addEventListener(`click`,e=>{e.stopPropagation();let t=document.getElementById(`imagePreviewLarge`);t&&t.src&&kp(t.src)});let a=document.getElementById(`imagePreviewEdit`);a&&a.addEventListener(`click`,e=>{e.stopPropagation(),Kp()});let o=document.getElementById(`imagePreviewPrev`),s=document.getElementById(`imagePreviewNext`);o&&o.addEventListener(`click`,e=>{e.stopPropagation(),Lp(-1)}),s&&s.addEventListener(`click`,e=>{e.stopPropagation(),Lp(1)}),document.addEventListener(`keydown`,t=>{e.classList.contains(`show`)&&(t.key===`Escape`?n():t.key===`ArrowLeft`?Lp(-1):t.key===`ArrowRight`&&Lp(1))}),e.addEventListener(`wheel`,n=>{if(!e.classList.contains(`show`)||gp)return;n.preventDefault();let r=t.getBoundingClientRect(),i=n.clientX-r.left-r.width/2,a=n.clientY-r.top-r.height/2,o=n.deltaY>0?-.15:.15,s=op,c=Math.max(.3,Math.min(5,op+o)),l=c/s;op=c,sp=i-l*(i-sp),cp=a-l*(a-cp),Ap()},{passive:!1}),t.addEventListener(`mousedown`,t=>{gp||!e.classList.contains(`show`)||op<=1||(t.preventDefault(),lp=!0,up=t.clientX,dp=t.clientY,fp=sp,pp=cp,Ap())}),document.addEventListener(`mousemove`,e=>{lp&&(sp=fp+(e.clientX-up),cp=pp+(e.clientY-dp),Ap())}),document.addEventListener(`mouseup`,()=>{lp&&(lp=!1,Ap())}),t.addEventListener(`dblclick`,()=>{gp||e.classList.contains(`show`)&&(op>1?jp():(op=2,sp=0,cp=0,Ap()))}),Wp()}function zp(e,t){let n=Math.max(e,t),r,i;n<=768?(r=n,i=.75):n<=1280?(r=768,i=.7):n<=2560?(r=1024,i=.65):n<=3840?(r=1280,i=.6):(r=1280,i=.55);let a=e,o=t;return n>r&&(e>t?(o=Math.round(r/e*t),a=r):(a=Math.round(r/t*e),o=r)),{targetWidth:a,targetHeight:o,quality:i}}function Bp(e){let t=new Image,n=URL.createObjectURL(e);t.onload=()=>{URL.revokeObjectURL(n);let r=new FileReader;r.onloadend=()=>{let e=r.result,{width:n,height:i}=t,{targetWidth:a,targetHeight:o,quality:s}=zp(n,i),c=document.createElement(`canvas`);c.width=a,c.height=o;let l=c.getContext(`2d`,{willReadFrequently:!0});l.imageSmoothingEnabled=!0,l.imageSmoothingQuality=`high`,l.drawImage(t,0,0,a,o);let u=c.toDataURL(`image/jpeg`,s);C.attachedImages.push({originalUrl:e,compressedUrl:u,width:a,height:o});let d=document.getElementById(`imagePreviewBar`),f=document.getElementById(`userInput`);d&&(d.style.display=``),Vp(),f&&f.focus()},r.readAsDataURL(e)},t.onerror=()=>{URL.revokeObjectURL(n),i.error(`[ChatManager] imageload failed`)},t.src=n}function Vp(){document.dispatchEvent(new CustomEvent(`input-attachments-changed`));let e=document.getElementById(`imagePreviewBar`);if(e){if(e.innerHTML=``,C.attachedImages.length===0){e.style.display=`none`;return}e.style.display=``,C.attachedImages.forEach((t,n)=>{let i=document.createElement(`div`);i.className=`image-preview-item`;let a=document.createElement(`img`);a.src=t.originalUrl||t.dataUrl,a.className=`image-preview-thumb`,a.title=r(`imagePreview.clickToEnlarge`),a.style.cursor=`zoom-in`,a.addEventListener(`click`,()=>{Mp(t.originalUrl||t.dataUrl,a)});let o=document.createElement(`button`);o.className=`image-preview-remove`,o.innerHTML=`×`,o.title=r(`imagePreview.removeImage`),o.addEventListener(`click`,e=>{e.stopPropagation(),C.attachedImages.splice(n,1),Vp()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}function Hp(e,t=null){let n=t||C.attachedImages;if(!C.enableImageInput||n.length===0)return e;let r=[{type:`text`,text:e}];for(let e of n)r.push({type:`image_url`,image_url:{url:e.compressedUrl||e.dataUrl,original_url:e.originalUrl||e.compressedUrl||e.dataUrl,width:e.width,height:e.height}});return r}function Up(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=e.filter(e=>e.type===`text`);return t.length===1?t[0].text:t}return e}function Wp(){W=document.getElementById(`imagePreviewEditCanvas`),K=document.getElementById(`imagePreviewPreviewCanvas`),W&&(G=W.getContext(`2d`,{willReadFrequently:!0}),G.lineCap=`round`,G.lineJoin=`round`),K&&(q=K.getContext(`2d`,{willReadFrequently:!0}),q.lineCap=`round`,q.lineJoin=`round`),Gp();let e=document.getElementById(`imagePreviewLarge`);e&&e.addEventListener(`load`,Xp)}function Gp(){let e=document.getElementById(`imagePreviewEditorToolbar`);if(!e)return;e.querySelectorAll(`[data-tool]`).forEach(t=>{t.addEventListener(`click`,()=>{e.querySelectorAll(`[data-tool]`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`),_p=t.dataset.tool,W&&(W.style.cursor=_p===`eraser`?`cell`:`crosshair`)})});let t=document.getElementById(`editorColorPicker`);t&&t.addEventListener(`input`,e=>{vp=e.target.value});let n=document.getElementById(`editorBrushSize`);n&&n.addEventListener(`input`,e=>{yp=parseInt(e.target.value)});let r=document.getElementById(`editorUndoBtn`);r&&r.addEventListener(`click`,am);let i=document.getElementById(`editorConfirmBtn`);i&&i.addEventListener(`click`,om);let a=document.getElementById(`editorCancelBtn`);a&&a.addEventListener(`click`,cm),document.addEventListener(`keydown`,t=>{if(!gp)return;let n={b:`brush`,r:`rectangle`,e:`ellipse`,a:`arrow`,l:`line`};n[t.key.toLowerCase()]&&!t.ctrlKey&&!t.metaKey&&(t.preventDefault(),_p=n[t.key.toLowerCase()],e.querySelectorAll(`[data-tool]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.tool===_p)})),(t.ctrlKey||t.metaKey)&&t.key===`z`&&(t.preventDefault(),am()),t.key===`Enter`&&(t.preventDefault(),om()),t.key===`Escape`&&(t.preventDefault(),cm())})}function Kp(){gp?Yp():qp()}function qp(){gp=!0,Op=[];let e=document.getElementById(`imagePreviewLarge`);if(!e||!e.src)return;jp(),e.style.transform=`none`,op=1,sp=0,cp=0,e.style.pointerEvents=`none`,e.style.zIndex=`1`,W&&(W.style.display=`block`,W.style.pointerEvents=`auto`,W.style.zIndex=`5`),K&&(K.style.display=`block`,K.style.pointerEvents=`none`,K.style.zIndex=`6`);let t=document.getElementById(`imagePreviewEditorToolbar`);t&&(t.style.display=`flex`);let n=document.getElementById(`imagePreviewEdit`);n&&(n.style.display=`none`);let r=document.getElementById(`imagePreviewDownload`);r&&(r.style.display=`none`);let i=document.getElementById(`imagePreviewViewport`);i&&i.addEventListener(`contextmenu`,Jp),setTimeout(()=>{Xp()},50),Op=[],W&&W.addEventListener(`mousedown`,Qp),document.addEventListener(`mousemove`,$p),document.addEventListener(`mouseup`,em)}function Jp(e){e.preventDefault()}function Yp(){gp=!1,xp=!1;let e=document.getElementById(`imagePreviewLarge`);e&&(e.style.pointerEvents=``,e.style.zIndex=``),W&&(W.style.display=`none`,W.removeEventListener(`mousedown`,Qp)),K&&(K.style.display=`none`,q.clearRect(0,0,K.width,K.height));let t=document.getElementById(`imagePreviewEditorToolbar`);t&&(t.style.display=`none`);let n=document.getElementById(`imagePreviewEdit`);n&&(n.style.display=``);let r=document.getElementById(`imagePreviewDownload`);r&&(r.style.display=``);let i=document.getElementById(`imagePreviewViewport`);i&&i.removeEventListener(`contextmenu`,Jp),document.removeEventListener(`mousemove`,$p),document.removeEventListener(`mouseup`,em)}function Xp(){let e=document.getElementById(`imagePreviewLarge`),t=document.getElementById(`imagePreviewViewport`);if(!e||!t||!W||!K)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=Math.round(n.width),a=Math.round(n.height);W.width=i,W.height=a,W.style.width=i+`px`,W.style.height=a+`px`,W.style.left=(r.width-i)/2+`px`,W.style.top=(r.height-a)/2+`px`,K.width=i,K.height=a,K.style.width=i+`px`,K.style.height=a+`px`,K.style.left=(r.width-i)/2+`px`,K.style.top=(r.height-a)/2+`px`}function Zp(e){if(!W)return{x:0,y:0};let t=W.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function Qp(e){if(!gp)return;e.preventDefault(),xp=!0;let t=Zp(e);Sp=t.x,Cp=t.y,wp=t.x,Tp=t.y,Ep=t.x,Dp=t.y,Op.push(W.toDataURL()),Op.length>20&&Op.shift()}function $p(e){if(!xp||!gp)return;e.preventDefault();let t=Zp(e);if(Ep=t.x,Dp=t.y,_p===`brush`){G.save(),G.beginPath(),G.strokeStyle=vp,G.lineWidth=yp,G.globalAlpha=bp,G.lineCap=`round`,G.lineJoin=`round`;let e=Ep-wp,t=Dp-Tp,n=Math.sqrt(e*e+t*t);if(n>2){let r=Math.ceil(n);for(let n=1;n<=r;n++){let i=n/r,a=wp+e*i,o=Tp+t*i;n===1&&G.moveTo(wp,Tp),G.lineTo(a,o)}}else G.moveTo(wp,Tp),G.lineTo(Ep,Dp);G.stroke(),G.restore(),wp=Ep,Tp=Dp}else if(_p===`eraser`){G.save(),G.beginPath(),G.lineWidth=yp*2,G.lineCap=`round`,G.lineJoin=`round`,G.globalCompositeOperation=`destination-out`;let e=Ep-wp,t=Dp-Tp,n=Math.sqrt(e*e+t*t);if(n>2){let r=Math.ceil(n);for(let n=1;n<=r;n++){let i=n/r,a=wp+e*i,o=Tp+t*i;n===1&&G.moveTo(wp,Tp),G.lineTo(a,o)}}else G.moveTo(wp,Tp),G.lineTo(Ep,Dp);G.stroke(),G.restore(),wp=Ep,Tp=Dp}else{if(!q)return;switch(q.clearRect(0,0,K.width,K.height),q.strokeStyle=vp,q.lineWidth=yp,q.globalAlpha=bp,q.lineCap=`round`,q.lineJoin=`round`,_p){case`rectangle`:tm();break;case`ellipse`:nm();break;case`arrow`:rm();break;case`line`:im();break}}}function em(){xp&&(xp=!1,_p!==`brush`&&_p!==`eraser`&&q&&(G.drawImage(K,0,0),q.clearRect(0,0,K.width,K.height)))}function tm(){let e=Math.min(Sp,Ep),t=Math.min(Cp,Dp),n=Math.abs(Ep-Sp),r=Math.abs(Dp-Cp);if(event.shiftKey){let e=Math.max(n,r),t=Ep>Sp?Sp:Sp-e,i=Dp>Cp?Cp:Cp-e;q.strokeRect(t,i,e,e)}else q.strokeRect(e,t,n,r)}function nm(){let e=Math.min(Sp,Ep),t=Math.min(Cp,Dp),n=Math.abs(Ep-Sp),r=Math.abs(Dp-Cp);if(event.shiftKey){let e=Math.max(n,r),t=Ep>Sp?Sp:Sp-e,i=Dp>Cp?Cp:Cp-e;q.beginPath(),q.ellipse(t+e/2,i+e/2,e/2,e/2,0,0,Math.PI*2),q.stroke()}else q.beginPath(),q.ellipse(e+n/2,t+r/2,n/2,r/2,0,0,Math.PI*2),q.stroke()}function rm(){let e=Math.atan2(Dp-Cp,Ep-Sp);q.beginPath(),q.moveTo(Sp,Cp),q.lineTo(Ep,Dp),q.stroke(),q.beginPath(),q.moveTo(Ep,Dp),q.lineTo(Ep-12*Math.cos(e-Math.PI/6),Dp-12*Math.sin(e-Math.PI/6)),q.moveTo(Ep,Dp),q.lineTo(Ep-12*Math.cos(e+Math.PI/6),Dp-12*Math.sin(e+Math.PI/6)),q.stroke()}function im(){q.beginPath(),q.moveTo(Sp,Cp),q.lineTo(Ep,Dp),q.stroke()}function am(){if(Op.length===0)return;let e=Op.pop(),t=new Image;t.onload=()=>{try{G.clearRect(0,0,W.width,W.height),G.drawImage(t,0,0,W.width,W.height)}catch(e){i.error(`Undo failed:`,e)}},t.onerror=()=>{i.error(`Failed to load undo image`),Op.length>0&&am()},t.src=e}function om(){let e=document.getElementById(`imagePreviewLarge`),t=document.getElementById(`imagePreviewOverlay`);if(!e||!W)return;let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let r=n.getContext(`2d`,{willReadFrequently:!0});r.drawImage(e,0,0);let i=e.naturalWidth/W.width,a=e.naturalHeight/W.height;r.save(),r.scale(i,a),r.drawImage(W,0,0),r.restore(),sm(n.toDataURL(`image/jpeg`,.85)),Yp(),t.classList.remove(`show`),jp()}function sm(e){let t=document.getElementById(`imagePreviewLarge`).src,n=document.getElementById(`imagePreviewLarge`),r=C.attachedImages.findIndex(e=>e.originalUrl===t||e.compressedUrl===t);if(r!==-1){let t=n?.naturalWidth||C.attachedImages[r].width,i=n?.naturalHeight||C.attachedImages[r].height;C.attachedImages[r]={originalUrl:e,compressedUrl:e,width:t,height:i},Vp()}let i=document.getElementById(`imagePreviewLarge`);i&&(i.src=e)}function cm(){G&&G.clearRect(0,0,W.width,W.height),Op=[],Yp()}var lm=t({attachFiles:()=>Dm,buildFileContentText:()=>jm,clearFiles:()=>km,extractFileContent:()=>vm,formatFileSize:()=>pm,getAgentConnectionInfo:()=>ym,getFileCategory:()=>dm,getFileIcon:()=>fm,processFile:()=>Em,removeFile:()=>Om,renderFilePreviews:()=>Am,runImagePipeline:()=>Tm,uploadFileToAgent:()=>xm});n(`zh`,{fileExtract:{fileReadFailed:`文件读取失败`,oldDocNotSupported:`旧版 .doc 格式不支持,请用 Word 另存为 .docx 格式后再试`,agentNotPaired:`Agent 未配对`,agentUploadFailed:`Agent 上传失败 ({status}): {error}`,unsupportedFormat:`暂不支持 "{name}" 格式的浏览器端提取,请连接 Agent 后再试`,oldDocNotSupportedBrowser:`旧版 .doc 格式浏览器不支持,请用 Word 另存为 .docx 格式后再试`,extracting:`提取中...`,failed:`失败`,extractFailed:`提取失败`,removeFile:`移除文件`,workspaceFileMarker:`[工作目录文件: {path} (原名: {name})]`,truncated:`...(内容已截断)`,fileContentMarker:`[文件内容: {name}]`}}),n(`en`,{fileExtract:{fileReadFailed:`File read failed`,oldDocNotSupported:`Legacy .doc format is not supported. Please save as .docx in Word and try again.`,agentNotPaired:`Agent not paired`,agentUploadFailed:`Agent upload failed ({status}): {error}`,unsupportedFormat:`Browser-side extraction for "{name}" is not supported. Please connect an Agent and try again.`,oldDocNotSupportedBrowser:`Legacy .doc format is not supported in the browser. Please save as .docx in Word and try again.`,extracting:`Extracting...`,failed:`Failed`,extractFailed:`Extraction failed`,removeFile:`Remove file`,workspaceFileMarker:`[Workspace file: {path} (original name: {name})]`,truncated:`...(content truncated)`,fileContentMarker:`[File content: {name}]`}});var um=`.txt,.md,.json,.js,.jsx,.ts,.tsx,.html,.css,.scss,.less,.xml,.yaml,.yml,.py,.java,.c,.cpp,.h,.go,.rs,.rb,.php,.sql,.sh,.bash,.zsh,.cfg,.ini,.toml,.conf,.log,.csv,.tsv,.env,.gitignore,.vue,.svelte,.astro,.rtf,.svg,.bat,.ps1,.makefile,.cmake,.gradle,.properties`.split(`,`);function dm(e){let t=e.toLowerCase();return t.endsWith(`.pdf`)?`pdf`:t.endsWith(`.docx`)?`docx`:t.endsWith(`.doc`)?`doc`:t.endsWith(`.xlsx`)||t.endsWith(`.xls`)?`xlsx`:um.some(e=>t.endsWith(e))?`text`:`unknown`}function fm(e){switch(dm(e)){case`pdf`:return`📄`;case`docx`:case`doc`:return`📝`;case`xlsx`:return`📊`;case`text`:return`📃`;default:return`📎`}}function pm(e){return e<1024?e+` B`:e<1024*1024?(e/1024).toFixed(1)+` KB`:(e/(1024*1024)).toFixed(1)+` MB`}async function mm(e){return new Promise((t,n)=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>n(Error(r(`fileExtract.fileReadFailed`))),i.readAsText(e,`UTF-8`)})}async function hm(t){let n=await A(()=>import(`./pdf-DnVqBaAN.js`).then(t=>e(t.default,1)),__vite__mapDeps([4,1,5]));n.GlobalWorkerOptions.workerSrc=`libs/pdf.worker.min.js`;let r=await t.arrayBuffer(),i=await n.getDocument({data:r}).promise,a=[];for(let e=1;e<=i.numPages;e++){let t=(await(await i.getPage(e)).getTextContent()).items.map(e=>e.str).join(` `);a.push(t)}return a.join(`
|
|
689
|
+
</div>`}).join(``),t.querySelectorAll(`.export-session-item`).forEach(e=>{let t=e.querySelector(`.export-session-checkbox`);e.addEventListener(`click`,e=>{e.target!==t&&(t.checked=!t.checked),ep()})});let a=document.getElementById(`exportSelectAllBtn`),o=document.getElementById(`exportDeselectAllBtn`),s=document.getElementById(`exportSelectCurrentBtn`);a&&(a.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=!0}),ep()}),o&&(o.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=!1}),ep()}),s&&(s.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=e.dataset.sessionId===i}),ep()}),ep()}}catch(e){i.error(`[SidePanel] loadsession column table failed:`,e),t.innerHTML=`<div class="export-sessions-empty">${r(`exportImport.loadFailed`)}</div>`}e.classList.add(`show`)}}function ep(){document.querySelectorAll(`#exportSessionsList .export-session-checkbox`);let e=document.querySelectorAll(`#exportSessionsList .export-session-checkbox:checked`),t=document.getElementById(`exportSelectedCount`);t&&(t.textContent=r(`chatExport.selectedCount`,{count:e.length}));let n=document.getElementById(`exportSessionsOkBtn`);n&&(n.textContent=r(`exportImport.exportSelectedCount`,{count:e.length}),n.disabled=e.length===0,n.style.opacity=e.length===0?`0.5`:`1`)}function tp(){let e=document.getElementById(`exportSessionsModal`);e&&e.classList.remove(`show`)}async function np(){let e=document.querySelectorAll(`#exportSessionsList .export-session-checkbox:checked`),t=Array.from(e).map(e=>e.dataset.sessionId);if(t.length===0){P(r(`exportImport.selectAtLeastOne`),`warning`);return}try{let{list:e}=await ti({withActiveHistory:!1}),n=await Promise.all(e.filter(e=>t.includes(e.id)).map(async e=>await w(e.id)||e)),a={version:1,exportedAt:new Date().toISOString(),sessions:n.map(e=>({title:e.title||r(`exportImport.unnamedSession`),model:e.model,useTools:e.useTools,enabledTools:e.enabledTools,temperature:e.temperature,topP:e.topP,createdAt:e.createdAt,messageHistory:(e.messageHistory||[]).map(e=>({role:e.role,content:e.content||``,executionLog:e.executionLog||[],htmlContent:e.htmlContent||``,reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,messageId:e.messageId||``,timestamp:e.timestamp||``}))}))},o=new Date,s=o.getFullYear()+String(o.getMonth()+1).padStart(2,`0`)+String(o.getDate()).padStart(2,`0`)+`-`+String(o.getHours()).padStart(2,`0`)+String(o.getMinutes()).padStart(2,`0`)+String(o.getSeconds()).padStart(2,`0`),c=n.length,l=c===1?`ai-helper-${n[0].title.replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)}-${s}.aihelper.json`:`ai-helper-${c}sessions-${s}.aihelper.json`,u=JSON.stringify(a,null,2),d=new Blob([u],{type:`application/json;charset=utf-8;`}),f=URL.createObjectURL(d),p=document.createElement(`a`);p.href=f,p.download=l,document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(f),tp(),i.debug(`[SidePanel] sessionexported:`,l,`total `,c,`session`),P(r(`exportImport.exportSuccess`,{count:c}),`success`)}catch(e){i.error(`[SidePanel] export failed:`,e),P(r(`exportImport.exportFailed`,{message:e.message}),`error`)}}function rp(){let e=document.getElementById(`exportSessionsCloseBtn`),t=document.getElementById(`exportSessionsCancelBtn`),n=document.getElementById(`exportSessionsOkBtn`),r=document.getElementById(`exportSessionsModal`);e&&e.addEventListener(`click`,tp),t&&t.addEventListener(`click`,tp),n&&n.addEventListener(`click`,np),r&&r.addEventListener(`click`,e=>{e.target===r&&tp()})}function ip(){let e=document.getElementById(`importSessionsFile`);e&&(e.value=``,e.click())}async function ap(e){try{let t=await e.text(),n=JSON.parse(t),a=[];if(n.version&&n.sessions&&Array.isArray(n.sessions))a=n.sessions;else if(Array.isArray(n))a=n.length>0&&n[0].role?[{title:r(`exportImport.importedConversation`),messageHistory:n.map(e=>({role:e.role||`user`,content:e.content||``}))}]:(n.length>0&&n[0].title,n);else throw Error(r(`exportImport.unrecognizedFormat`));if(a.length===0){P(r(`exportImport.noImportableData`),`warning`);return}let o=await gi(a);await yo(),i.debug(`[SidePanel] import complete:`,o.length,`session`),P(r(`exportImport.importSuccess`,{count:o.length}),`success`)}catch(e){i.error(`[SidePanel] import failed:`,e),P(r(`exportImport.importFailed`,{message:e.message}),`error`)}}n(`zh`,{imagePreview:{clickToEnlarge:`点击查看大图`,removeImage:`移除图片`}}),n(`en`,{imagePreview:{clickToEnlarge:`Click to enlarge`,removeImage:`Remove image`}});var op=1,sp=0,cp=0,lp=!1,up=0,dp=0,fp=0,pp=0,mp=[],hp=0,gp=!1,_p=`brush`,vp=`#ff4757`,yp=4,bp=1,xp=!1,Sp=0,Cp=0,wp=0,Tp=0,Ep=0,Dp=0,Op=[],W=null,G=null,K=null,q=null;function kp(e){let t=document.createElement(`a`);t.href=e,t.download=`image_${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.jpg`,document.body.appendChild(t),t.click(),document.body.removeChild(t)}function Ap(){let e=document.getElementById(`imagePreviewLarge`);e&&(e.style.transform=`translate(${sp}px, ${cp}px) scale(${op})`,op>1?(e.classList.add(`zoomable`),lp?e.classList.add(`dragging`):e.classList.remove(`dragging`)):e.classList.remove(`zoomable`,`dragging`))}function jp(){op=1,sp=0,cp=0,lp=!1,Ap()}function Mp(e,t){let n=document.getElementById(`imagePreviewOverlay`),r=document.getElementById(`imagePreviewLarge`),i=document.getElementById(`imagePreviewEdit`);if(!n||!r)return;let a=t&&t.closest(`.user-message-images`);i&&(i.style.display=a?`none`:``),Np(e,t),Pp(),Ip(e),n.classList.add(`show`)}function Np(e,t){mp=[],t&&(t.closest(`.image-preview-bar`)||t.classList.contains(`image-preview-thumb`)?document.querySelectorAll(`.image-preview-thumb`).forEach(e=>{e.src&&mp.push(e.src)}):t.closest(`.user-message-images`)&&t.closest(`.user-message-images`).querySelectorAll(`.user-message-image`).forEach(e=>{e.src&&mp.push(e.src)})),mp.length===0&&document.querySelectorAll(`.image-preview-thumb, .user-message-image`).forEach(e=>{e.src&&mp.push(e.src)}),hp=mp.indexOf(e),hp===-1&&(mp.push(e),hp=mp.length-1)}function Pp(){let e=document.getElementById(`imagePreviewPrev`),t=document.getElementById(`imagePreviewNext`),n=document.getElementById(`imagePreviewCounter`);mp.length<=1?(e&&(e.style.display=`none`),t&&(t.style.display=`none`),n&&(n.style.display=`none`)):(e&&(e.style.display=``),t&&(t.style.display=``),n&&(n.style.display=``),Fp())}function Fp(){let e=document.getElementById(`imagePreviewPrev`),t=document.getElementById(`imagePreviewNext`),n=document.getElementById(`imagePreviewCounter`);e&&(e.disabled=!1),t&&(t.disabled=!1),n&&(n.textContent=`${hp+1} / ${mp.length}`)}function Ip(e){let t=document.getElementById(`imagePreviewLarge`);t&&(jp(),t.src=e)}function Lp(e){let t=mp.length;t!==0&&(hp=(hp+e+t)%t,Ip(mp[hp]),Fp())}function Rp(){let e=document.getElementById(`imagePreviewOverlay`);if(!e||e.dataset.initialized)return;e.dataset.initialized=`true`;let t=document.getElementById(`imagePreviewLarge`),n=()=>{e.classList.remove(`show`),jp()},r=e.querySelector(`.image-preview-close`);r&&r.addEventListener(`click`,n);let i=document.getElementById(`imagePreviewDownload`);i&&i.addEventListener(`click`,e=>{e.stopPropagation();let t=document.getElementById(`imagePreviewLarge`);t&&t.src&&kp(t.src)});let a=document.getElementById(`imagePreviewEdit`);a&&a.addEventListener(`click`,e=>{e.stopPropagation(),Kp()});let o=document.getElementById(`imagePreviewPrev`),s=document.getElementById(`imagePreviewNext`);o&&o.addEventListener(`click`,e=>{e.stopPropagation(),Lp(-1)}),s&&s.addEventListener(`click`,e=>{e.stopPropagation(),Lp(1)}),document.addEventListener(`keydown`,t=>{e.classList.contains(`show`)&&(t.key===`Escape`?n():t.key===`ArrowLeft`?Lp(-1):t.key===`ArrowRight`&&Lp(1))}),e.addEventListener(`wheel`,n=>{if(!e.classList.contains(`show`)||gp)return;n.preventDefault();let r=t.getBoundingClientRect(),i=n.clientX-r.left-r.width/2,a=n.clientY-r.top-r.height/2,o=n.deltaY>0?-.15:.15,s=op,c=Math.max(.3,Math.min(5,op+o)),l=c/s;op=c,sp=i-l*(i-sp),cp=a-l*(a-cp),Ap()},{passive:!1}),t.addEventListener(`mousedown`,t=>{gp||!e.classList.contains(`show`)||op<=1||(t.preventDefault(),lp=!0,up=t.clientX,dp=t.clientY,fp=sp,pp=cp,Ap())}),document.addEventListener(`mousemove`,e=>{lp&&(sp=fp+(e.clientX-up),cp=pp+(e.clientY-dp),Ap())}),document.addEventListener(`mouseup`,()=>{lp&&(lp=!1,Ap())}),t.addEventListener(`dblclick`,()=>{gp||e.classList.contains(`show`)&&(op>1?jp():(op=2,sp=0,cp=0,Ap()))}),Wp()}function zp(e,t){let n=Math.max(e,t),r,i;n<=768?(r=n,i=.75):n<=1280?(r=768,i=.7):n<=2560?(r=1024,i=.65):n<=3840?(r=1280,i=.6):(r=1280,i=.55);let a=e,o=t;return n>r&&(e>t?(o=Math.round(r/e*t),a=r):(a=Math.round(r/t*e),o=r)),{targetWidth:a,targetHeight:o,quality:i}}function Bp(e){let t=new Image,n=URL.createObjectURL(e);t.onload=()=>{URL.revokeObjectURL(n);let r=new FileReader;r.onloadend=()=>{let e=r.result,{width:n,height:i}=t,{targetWidth:a,targetHeight:o,quality:s}=zp(n,i),c=document.createElement(`canvas`);c.width=a,c.height=o;let l=c.getContext(`2d`,{willReadFrequently:!0});l.imageSmoothingEnabled=!0,l.imageSmoothingQuality=`high`,l.drawImage(t,0,0,a,o);let u=c.toDataURL(`image/jpeg`,s);C.attachedImages.push({originalUrl:e,compressedUrl:u,width:a,height:o});let d=document.getElementById(`imagePreviewBar`),f=document.getElementById(`userInput`);d&&(d.style.display=``),Vp(),f&&f.focus()},r.readAsDataURL(e)},t.onerror=()=>{URL.revokeObjectURL(n),i.error(`[ChatManager] imageload failed`)},t.src=n}function Vp(){document.dispatchEvent(new CustomEvent(`input-attachments-changed`));let e=document.getElementById(`imagePreviewBar`);if(e){if(e.innerHTML=``,C.attachedImages.length===0){e.style.display=`none`;return}e.style.display=``,C.attachedImages.forEach((t,n)=>{let i=document.createElement(`div`);i.className=`image-preview-item`;let a=document.createElement(`img`);a.src=t.originalUrl||t.dataUrl,a.className=`image-preview-thumb`,a.title=r(`imagePreview.clickToEnlarge`),a.style.cursor=`zoom-in`,a.addEventListener(`click`,()=>{Mp(t.originalUrl||t.dataUrl,a)});let o=document.createElement(`button`);o.className=`image-preview-remove`,o.innerHTML=`×`,o.title=r(`imagePreview.removeImage`),o.addEventListener(`click`,e=>{e.stopPropagation(),C.attachedImages.splice(n,1),Vp()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}function Hp(e,t=null){let n=t||C.attachedImages;if(!C.enableImageInput||n.length===0)return e;let r=[{type:`text`,text:e}];for(let e of n)r.push({type:`image_url`,image_url:{url:e.compressedUrl||e.dataUrl,original_url:e.originalUrl||e.compressedUrl||e.dataUrl,width:e.width,height:e.height}});return r}function Up(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=e.filter(e=>e.type===`text`);return t.length===1?t[0].text:t}return e}function Wp(){W=document.getElementById(`imagePreviewEditCanvas`),K=document.getElementById(`imagePreviewPreviewCanvas`),W&&(G=W.getContext(`2d`,{willReadFrequently:!0}),G.lineCap=`round`,G.lineJoin=`round`),K&&(q=K.getContext(`2d`,{willReadFrequently:!0}),q.lineCap=`round`,q.lineJoin=`round`),Gp();let e=document.getElementById(`imagePreviewLarge`);e&&e.addEventListener(`load`,Xp)}function Gp(){let e=document.getElementById(`imagePreviewEditorToolbar`);if(!e)return;e.querySelectorAll(`[data-tool]`).forEach(t=>{t.addEventListener(`click`,()=>{e.querySelectorAll(`[data-tool]`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`),_p=t.dataset.tool,W&&(W.style.cursor=_p===`eraser`?`cell`:`crosshair`)})});let t=document.getElementById(`editorColorPicker`);t&&t.addEventListener(`input`,e=>{vp=e.target.value});let n=document.getElementById(`editorBrushSize`);n&&n.addEventListener(`input`,e=>{yp=parseInt(e.target.value)});let r=document.getElementById(`editorUndoBtn`);r&&r.addEventListener(`click`,am);let i=document.getElementById(`editorConfirmBtn`);i&&i.addEventListener(`click`,om);let a=document.getElementById(`editorCancelBtn`);a&&a.addEventListener(`click`,cm),document.addEventListener(`keydown`,t=>{if(!gp)return;let n={b:`brush`,r:`rectangle`,e:`ellipse`,a:`arrow`,l:`line`};n[t.key.toLowerCase()]&&!t.ctrlKey&&!t.metaKey&&(t.preventDefault(),_p=n[t.key.toLowerCase()],e.querySelectorAll(`[data-tool]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.tool===_p)})),(t.ctrlKey||t.metaKey)&&t.key===`z`&&(t.preventDefault(),am()),t.key===`Enter`&&(t.preventDefault(),om()),t.key===`Escape`&&(t.preventDefault(),cm())})}function Kp(){gp?Yp():qp()}function qp(){gp=!0,Op=[];let e=document.getElementById(`imagePreviewLarge`);if(!e||!e.src)return;jp(),e.style.transform=`none`,op=1,sp=0,cp=0,e.style.pointerEvents=`none`,e.style.zIndex=`1`,W&&(W.style.display=`block`,W.style.pointerEvents=`auto`,W.style.zIndex=`5`),K&&(K.style.display=`block`,K.style.pointerEvents=`none`,K.style.zIndex=`6`);let t=document.getElementById(`imagePreviewEditorToolbar`);t&&(t.style.display=`flex`);let n=document.getElementById(`imagePreviewEdit`);n&&(n.style.display=`none`);let r=document.getElementById(`imagePreviewDownload`);r&&(r.style.display=`none`);let i=document.getElementById(`imagePreviewViewport`);i&&i.addEventListener(`contextmenu`,Jp),setTimeout(()=>{Xp()},50),Op=[],W&&W.addEventListener(`mousedown`,Qp),document.addEventListener(`mousemove`,$p),document.addEventListener(`mouseup`,em)}function Jp(e){e.preventDefault()}function Yp(){gp=!1,xp=!1;let e=document.getElementById(`imagePreviewLarge`);e&&(e.style.pointerEvents=``,e.style.zIndex=``),W&&(W.style.display=`none`,W.removeEventListener(`mousedown`,Qp)),K&&(K.style.display=`none`,q.clearRect(0,0,K.width,K.height));let t=document.getElementById(`imagePreviewEditorToolbar`);t&&(t.style.display=`none`);let n=document.getElementById(`imagePreviewEdit`);n&&(n.style.display=``);let r=document.getElementById(`imagePreviewDownload`);r&&(r.style.display=``);let i=document.getElementById(`imagePreviewViewport`);i&&i.removeEventListener(`contextmenu`,Jp),document.removeEventListener(`mousemove`,$p),document.removeEventListener(`mouseup`,em)}function Xp(){let e=document.getElementById(`imagePreviewLarge`),t=document.getElementById(`imagePreviewViewport`);if(!e||!t||!W||!K)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=Math.round(n.width),a=Math.round(n.height);W.width=i,W.height=a,W.style.width=i+`px`,W.style.height=a+`px`,W.style.left=(r.width-i)/2+`px`,W.style.top=(r.height-a)/2+`px`,K.width=i,K.height=a,K.style.width=i+`px`,K.style.height=a+`px`,K.style.left=(r.width-i)/2+`px`,K.style.top=(r.height-a)/2+`px`}function Zp(e){if(!W)return{x:0,y:0};let t=W.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function Qp(e){if(!gp)return;e.preventDefault(),xp=!0;let t=Zp(e);Sp=t.x,Cp=t.y,wp=t.x,Tp=t.y,Ep=t.x,Dp=t.y,Op.push(W.toDataURL()),Op.length>20&&Op.shift()}function $p(e){if(!xp||!gp)return;e.preventDefault();let t=Zp(e);if(Ep=t.x,Dp=t.y,_p===`brush`){G.save(),G.beginPath(),G.strokeStyle=vp,G.lineWidth=yp,G.globalAlpha=bp,G.lineCap=`round`,G.lineJoin=`round`;let e=Ep-wp,t=Dp-Tp,n=Math.sqrt(e*e+t*t);if(n>2){let r=Math.ceil(n);for(let n=1;n<=r;n++){let i=n/r,a=wp+e*i,o=Tp+t*i;n===1&&G.moveTo(wp,Tp),G.lineTo(a,o)}}else G.moveTo(wp,Tp),G.lineTo(Ep,Dp);G.stroke(),G.restore(),wp=Ep,Tp=Dp}else if(_p===`eraser`){G.save(),G.beginPath(),G.lineWidth=yp*2,G.lineCap=`round`,G.lineJoin=`round`,G.globalCompositeOperation=`destination-out`;let e=Ep-wp,t=Dp-Tp,n=Math.sqrt(e*e+t*t);if(n>2){let r=Math.ceil(n);for(let n=1;n<=r;n++){let i=n/r,a=wp+e*i,o=Tp+t*i;n===1&&G.moveTo(wp,Tp),G.lineTo(a,o)}}else G.moveTo(wp,Tp),G.lineTo(Ep,Dp);G.stroke(),G.restore(),wp=Ep,Tp=Dp}else{if(!q)return;switch(q.clearRect(0,0,K.width,K.height),q.strokeStyle=vp,q.lineWidth=yp,q.globalAlpha=bp,q.lineCap=`round`,q.lineJoin=`round`,_p){case`rectangle`:tm();break;case`ellipse`:nm();break;case`arrow`:rm();break;case`line`:im();break}}}function em(){xp&&(xp=!1,_p!==`brush`&&_p!==`eraser`&&q&&(G.drawImage(K,0,0),q.clearRect(0,0,K.width,K.height)))}function tm(){let e=Math.min(Sp,Ep),t=Math.min(Cp,Dp),n=Math.abs(Ep-Sp),r=Math.abs(Dp-Cp);if(event.shiftKey){let e=Math.max(n,r),t=Ep>Sp?Sp:Sp-e,i=Dp>Cp?Cp:Cp-e;q.strokeRect(t,i,e,e)}else q.strokeRect(e,t,n,r)}function nm(){let e=Math.min(Sp,Ep),t=Math.min(Cp,Dp),n=Math.abs(Ep-Sp),r=Math.abs(Dp-Cp);if(event.shiftKey){let e=Math.max(n,r),t=Ep>Sp?Sp:Sp-e,i=Dp>Cp?Cp:Cp-e;q.beginPath(),q.ellipse(t+e/2,i+e/2,e/2,e/2,0,0,Math.PI*2),q.stroke()}else q.beginPath(),q.ellipse(e+n/2,t+r/2,n/2,r/2,0,0,Math.PI*2),q.stroke()}function rm(){let e=Math.atan2(Dp-Cp,Ep-Sp);q.beginPath(),q.moveTo(Sp,Cp),q.lineTo(Ep,Dp),q.stroke(),q.beginPath(),q.moveTo(Ep,Dp),q.lineTo(Ep-12*Math.cos(e-Math.PI/6),Dp-12*Math.sin(e-Math.PI/6)),q.moveTo(Ep,Dp),q.lineTo(Ep-12*Math.cos(e+Math.PI/6),Dp-12*Math.sin(e+Math.PI/6)),q.stroke()}function im(){q.beginPath(),q.moveTo(Sp,Cp),q.lineTo(Ep,Dp),q.stroke()}function am(){if(Op.length===0)return;let e=Op.pop(),t=new Image;t.onload=()=>{try{G.clearRect(0,0,W.width,W.height),G.drawImage(t,0,0,W.width,W.height)}catch(e){i.error(`Undo failed:`,e)}},t.onerror=()=>{i.error(`Failed to load undo image`),Op.length>0&&am()},t.src=e}function om(){let e=document.getElementById(`imagePreviewLarge`),t=document.getElementById(`imagePreviewOverlay`);if(!e||!W)return;let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let r=n.getContext(`2d`,{willReadFrequently:!0});r.drawImage(e,0,0);let i=e.naturalWidth/W.width,a=e.naturalHeight/W.height;r.save(),r.scale(i,a),r.drawImage(W,0,0),r.restore(),sm(n.toDataURL(`image/jpeg`,.85)),Yp(),t.classList.remove(`show`),jp()}function sm(e){let t=document.getElementById(`imagePreviewLarge`).src,n=document.getElementById(`imagePreviewLarge`),r=C.attachedImages.findIndex(e=>e.originalUrl===t||e.compressedUrl===t);if(r!==-1){let t=n?.naturalWidth||C.attachedImages[r].width,i=n?.naturalHeight||C.attachedImages[r].height;C.attachedImages[r]={originalUrl:e,compressedUrl:e,width:t,height:i},Vp()}let i=document.getElementById(`imagePreviewLarge`);i&&(i.src=e)}function cm(){G&&G.clearRect(0,0,W.width,W.height),Op=[],Yp()}var lm=t({attachFiles:()=>Dm,buildFileContentText:()=>jm,clearFiles:()=>km,extractFileContent:()=>vm,formatFileSize:()=>pm,getAgentConnectionInfo:()=>ym,getFileCategory:()=>dm,getFileIcon:()=>fm,processFile:()=>Em,removeFile:()=>Om,renderFilePreviews:()=>Am,runImagePipeline:()=>Tm,uploadFileToAgent:()=>xm});n(`zh`,{fileExtract:{fileReadFailed:`文件读取失败`,oldDocNotSupported:`旧版 .doc 格式不支持,请用 Word 另存为 .docx 格式后再试`,agentNotPaired:`Agent 未配对`,agentUploadFailed:`Agent 上传失败 ({status}): {error}`,unsupportedFormat:`暂不支持 "{name}" 格式的浏览器端提取,请连接 Agent 后再试`,oldDocNotSupportedBrowser:`旧版 .doc 格式浏览器不支持,请用 Word 另存为 .docx 格式后再试`,extracting:`提取中...`,failed:`失败`,extractFailed:`提取失败`,removeFile:`移除文件`,workspaceFileMarker:`[工作目录文件: {path} (原名: {name})]`,truncated:`...(内容已截断)`,fileContentMarker:`[文件内容: {name}]`}}),n(`en`,{fileExtract:{fileReadFailed:`File read failed`,oldDocNotSupported:`Legacy .doc format is not supported. Please save as .docx in Word and try again.`,agentNotPaired:`Agent not paired`,agentUploadFailed:`Agent upload failed ({status}): {error}`,unsupportedFormat:`Browser-side extraction for "{name}" is not supported. Please connect an Agent and try again.`,oldDocNotSupportedBrowser:`Legacy .doc format is not supported in the browser. Please save as .docx in Word and try again.`,extracting:`Extracting...`,failed:`Failed`,extractFailed:`Extraction failed`,removeFile:`Remove file`,workspaceFileMarker:`[Workspace file: {path} (original name: {name})]`,truncated:`...(content truncated)`,fileContentMarker:`[File content: {name}]`}});var um=`.txt,.md,.json,.js,.jsx,.ts,.tsx,.html,.css,.scss,.less,.xml,.yaml,.yml,.py,.java,.c,.cpp,.h,.go,.rs,.rb,.php,.sql,.sh,.bash,.zsh,.cfg,.ini,.toml,.conf,.log,.csv,.tsv,.env,.gitignore,.vue,.svelte,.astro,.rtf,.svg,.bat,.ps1,.makefile,.cmake,.gradle,.properties`.split(`,`);function dm(e){let t=e.toLowerCase();return t.endsWith(`.pdf`)?`pdf`:t.endsWith(`.docx`)?`docx`:t.endsWith(`.doc`)?`doc`:t.endsWith(`.xlsx`)||t.endsWith(`.xls`)?`xlsx`:um.some(e=>t.endsWith(e))?`text`:`unknown`}function fm(e){switch(dm(e)){case`pdf`:return`📄`;case`docx`:case`doc`:return`📝`;case`xlsx`:return`📊`;case`text`:return`📃`;default:return`📎`}}function pm(e){return e<1024?e+` B`:e<1024*1024?(e/1024).toFixed(1)+` KB`:(e/(1024*1024)).toFixed(1)+` MB`}async function mm(e){return new Promise((t,n)=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>n(Error(r(`fileExtract.fileReadFailed`))),i.readAsText(e,`UTF-8`)})}async function hm(t){let n=await A(()=>import(`./pdf-DnVqBaAN.js`).then(t=>e(t.default,1)),__vite__mapDeps([4,1,5]));n.GlobalWorkerOptions.workerSrc=`libs/pdf.worker.min.js`;let r=await t.arrayBuffer(),i=await n.getDocument({data:r}).promise,a=[];for(let e=1;e<=i.numPages;e++){let t=(await(await i.getPage(e)).getTextContent()).items.map(e=>e.str).join(` `);a.push(t)}return a.join(`
|
|
690
690
|
|
|
691
691
|
`)}async function gm(t){let n=(await A(async()=>{let{default:t}=await import(`./lib-YwkWjNcC.js`).then(t=>e(t.default,1));return{default:t}},__vite__mapDeps([6,1,7,5]))).default,r=await t.arrayBuffer();return(await n.extractRawText({arrayBuffer:r})).value}async function _m(e){let t=await A(()=>import(`./xlsx-DGkz7cnk.js`),[]),n=await e.arrayBuffer(),r=t.read(n,{type:`array`}),i=[];for(let e of r.SheetNames){let n=r.Sheets[e],a=t.utils.sheet_to_csv(n);a.trim()&&i.push(`=== Sheet: ${e} ===\n${a}`)}return i.join(`
|
|
692
692
|
|
|
@@ -728,7 +728,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
728
728
|
<div class="bookmark-panel-empty">${r(`bookmark.empty`)}</div>
|
|
729
729
|
</div>
|
|
730
730
|
</div>
|
|
731
|
-
`,hn(`bookmark`).appendChild(e);let t=document.getElementById(`bookmarkPanelToggle`),n=document.getElementById(`bookmarkPanel`),a=document.getElementById(`bookmarkSearchInput`),o=document.getElementById(`bookmarkPanelClose`);C.bookmarkSearchHistory=[],C.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.get([`bookmarkSearchHistory`],e=>{e.bookmarkSearchHistory&&(C.bookmarkSearchHistory=e.bookmarkSearchHistory)})}catch{}function s(e){if(!e||!e.trim())return;let t=e.trim(),n=C.bookmarkSearchHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),C.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.set({bookmarkSearchHistory:n})}catch{}}t.addEventListener(`click`,()=>{n.classList.contains(`expanded`)?(n.classList.remove(`expanded`),
|
|
731
|
+
`,hn(`bookmark`).appendChild(e);let t=document.getElementById(`bookmarkPanelToggle`),n=document.getElementById(`bookmarkPanel`),a=document.getElementById(`bookmarkSearchInput`),o=document.getElementById(`bookmarkPanelClose`);C.bookmarkSearchHistory=[],C.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.get([`bookmarkSearchHistory`],e=>{e.bookmarkSearchHistory&&(C.bookmarkSearchHistory=e.bookmarkSearchHistory)})}catch{}function s(e){if(!e||!e.trim())return;let t=e.trim(),n=C.bookmarkSearchHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),C.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.set({bookmarkSearchHistory:n})}catch{}}t.addEventListener(`click`,()=>{n.classList.contains(`expanded`)?(n.classList.remove(`expanded`),Le(n)):(Vm(a.value),n.classList.add(`expanded`),Fe(n))}),o.addEventListener(`click`,()=>{n.classList.remove(`expanded`),Le(n)});let c=document.getElementById(`bookmarkSearchClear`);a.addEventListener(`input`,()=>{let e=a.value.trim();Vm(e),c.style.display=e?``:`none`}),c.addEventListener(`click`,()=>{a.value=``,c.style.display=`none`,C.bookmarkSearchHistoryIndex=-1,Vm()}),a.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.preventDefault();let t=a.value.trim();t&&(s(t),Vm(t))}else if(e.key===`Escape`)C.bookmarkSearchHistoryIndex>=0&&(C.bookmarkSearchHistoryIndex=-1,a.value=``,Vm(),c.style.display=`none`);else if(e.key===`ArrowUp`){e.preventDefault();let t=C.bookmarkSearchHistory;if(t.length===0)return;C.bookmarkSearchHistoryIndex===-1?C.bookmarkSearchHistoryIndex=t.length-1:C.bookmarkSearchHistoryIndex>0&&C.bookmarkSearchHistoryIndex--,a.value=t[C.bookmarkSearchHistoryIndex]||``,c.style.display=a.value?``:`none`,Vm(a.value)}else if(e.key===`ArrowDown`){e.preventDefault();let t=C.bookmarkSearchHistory;C.bookmarkSearchHistoryIndex>=0&&C.bookmarkSearchHistoryIndex<t.length-1?(C.bookmarkSearchHistoryIndex++,a.value=t[C.bookmarkSearchHistoryIndex]||``):(C.bookmarkSearchHistoryIndex=-1,a.value=``),c.style.display=a.value?``:`none`,Vm(a.value)}}),document.getElementById(`bookmarkPanelContent`).addEventListener(`click`,async e=>{let t=e.target.closest(`.bookmark-item`);if(!t)return;let n=t.dataset.bookmarkId,r=t.dataset.sessionId,i=t.dataset.messageId;if(e.target.closest(`.bookmark-item-remove`)){e.stopPropagation(),await Im(n),Vm(),Km();return}if(e.target.closest(`.bookmark-item-pin`)){e.stopPropagation();let t=C.bookmarks.find(e=>e.id===n);t&&(await Lm(n,!t.pinned),Vm());return}await Wm(r,i)}),i.debug(`[BookmarkPanel] bookmark panelinitializing`)}function Vm(e){let t=document.getElementById(`bookmarkPanelContent`),n=document.getElementById(`bookmarkPanelCount`);if(!t||!n)return;let i=C.activeSessionId,a=Rm(i),o=i?C.bookmarks.filter(e=>e.sessionId!==i).sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:t.createdAt-e.createdAt):[],s=(e||``).trim(),c=s.toLowerCase(),l=c.includes(`&`)||c.includes(`|`);if(s){let e=e=>{let t=((e.content||``)+` `+(e.sessionTitle||``)).toLowerCase();if(l){let e=c.split(`|`).map(e=>e.trim()).filter(Boolean);for(let n of e){let e=n.split(`&`).map(e=>e.trim()).filter(Boolean);if(e.length!==0&&e.every(e=>t.includes(e)))return!0}return!1}return t.includes(c)};a=a.filter(e),o=o.filter(e)}let u=C.bookmarks.length,d=a.length+o.length;if(c?n.textContent=r(`bookmark.searchCount`,{filtered:d,total:u}):n.textContent=u>0?r(`bookmark.countResult`,{count:u}):``,u===0){t.innerHTML=`<div class="bookmark-panel-empty">${r(`bookmark.empty`)}</div>`,Gm();return}if(c&&d===0){t.innerHTML=`<div class="bookmark-panel-empty">${r(`bookmark.noMatch`)}</div>`,Gm();return}let f=``;a.length>0&&(f+=`<div class="bookmark-section">
|
|
732
732
|
<div class="bookmark-section-title">${r(`searchPanel.currentSession`)}</div>
|
|
733
733
|
${Hm(a,c)}
|
|
734
734
|
</div>`),o.length>0&&(f+=`<div class="bookmark-section">
|
|
@@ -737,10 +737,10 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
737
737
|
</div>`),t.innerHTML=f,Gm()}function Hm(e,t){let n=(t||``).trim().toLowerCase();return e.map(e=>{let t=e.content||``,i=e.sessionTitle||r(`searchPanel.unknownSession`),a=t.length>60?t.substring(0,60)+`...`:t,o=i;n&&(a=Um(a,n),o=Um(o,n)),a||=r(`bookmark.noTextContent`);let s=e.pinned?`pinned`:``,c=new Date(e.createdAt).toLocaleString(`zh-CN`,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`});return`
|
|
738
738
|
<div class="bookmark-item ${s}" data-bookmark-id="${e.id}" data-session-id="${e.sessionId}" data-message-id="${e.messageId}">
|
|
739
739
|
<div class="bookmark-item-header">
|
|
740
|
-
<span class="bookmark-item-session" title="${
|
|
740
|
+
<span class="bookmark-item-session" title="${I(i)}">${o}</span>
|
|
741
741
|
<span class="bookmark-item-time">${c}</span>
|
|
742
742
|
</div>
|
|
743
|
-
<div class="bookmark-item-content" title="${
|
|
743
|
+
<div class="bookmark-item-content" title="${I(t)}">${a}</div>
|
|
744
744
|
<div class="bookmark-item-actions">
|
|
745
745
|
<button class="bookmark-item-pin" title="${e.pinned?r(`bookmark.unpinTitle`):r(`bookmark.pinTitle`)}">
|
|
746
746
|
<svg viewBox="0 0 24 24" fill="${e.pinned?`currentColor`:`none`}" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
@@ -755,21 +755,21 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
755
755
|
</button>
|
|
756
756
|
</div>
|
|
757
757
|
</div>
|
|
758
|
-
`}).join(``)}function Um(e,t){if(!t)return e;let n=
|
|
758
|
+
`}).join(``)}function Um(e,t){if(!t)return e;let n=I(e),r=t.split(/[&|]/).map(e=>e.trim()).filter(Boolean);if(r.length===0)return n;let i=r.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),a=RegExp(`(${i.join(`|`)})`,`gi`);return n.replace(a,`<mark class="bookmark-highlight-match">$1</mark>`)}async function Wm(e,t){if(!(!e||!t)){if(C.activeSessionId!==e)try{let n=C.activeSessionId;if(await oi(e)===!1||C.activeSessionId!==e){await Fm(e,t),Vm(),P(r(`bookmark.sessionNotExistToast`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await A(async()=>{let{renderSessionTabs:e}=await Promise.resolve().then(()=>mo);return{renderSessionTabs:e}},void 0);e()}catch(e){i.warn(`[BookmarkPanel] refreshsessionTab failed:`,e)}}catch(e){i.error(`[BookmarkPanel] switchsession failed:`,e);return}setTimeout(()=>{let n=document.getElementById(`chatContainer`);if(!n)return;let i=n.querySelector(`.message[data-message-id="${t}"]`);i?(i.scrollIntoView({behavior:`instant`,block:`nearest`}),i.classList.add(`bookmark-highlight`),setTimeout(()=>{i.classList.remove(`bookmark-highlight`)},2e3)):Fm(e,t).then(()=>{Vm(),P(r(`bookmark.messageNotExistToast`),`warning`)})},500)}}function Gm(){let e=document.getElementById(`bookmarkPanelContainer`),t=C.bookmarks.length;e&&(e.style.display=t>0?``:`none`)}function Km(){let e=document.getElementById(`chatContainer`);e&&e.querySelectorAll(`.message.assistant`).forEach(e=>{let t=e.querySelector(`.bookmark-btn`);if(!t)return;let n=e.dataset.messageId,r=C.activeSessionId;qm(t,r,n)})}function qm(e,t,n){Nm(t,n)?(e.classList.add(`bookmarked`),e.title=r(`bookmark.removeBookmarkTitle`),e.querySelector(`svg`).setAttribute(`fill`,`currentColor`)):(e.classList.remove(`bookmarked`),e.title=r(`bookmark.addBookmarkTitle`),e.querySelector(`svg`).setAttribute(`fill`,`none`))}function Jm(e,t=`win32`){let n=String(e||``).trim();if(!n)return[];if(t===`win32`){if(n.startsWith(`\\\\`))return[{name:n,path:n}];let e=n.replace(/\//g,`\\`).split(`\\`).filter(Boolean);if(!e.length)return[];let t=[],r=``;return e.forEach((e,n)=>{r=n===0?`${e}\\`:r.endsWith(`\\`)?`${r}${e}`:`${r}\\${e}`,t.push({name:e,path:r})}),t}let r=n.split(`/`).filter(Boolean),i=[{name:`/`,path:`/`}],a=``;for(let e of r)a=`${a}/${e}`,i.push({name:e,path:a});return i}function Ym(e){switch(e){case`path_not_found`:return`workspace.browseNotFound`;case`not_a_directory`:return`workspace.browseNotDir`;case`permission_denied`:return`workspace.browsePermissionDenied`;case`bad_path`:case`path_too_long`:return`workspace.browseBadPath`;case`timeout`:case`client-timeout`:return`workspace.browseTimeout`;case`rate_limited`:case`too-frequent`:return`workspace.browseRateLimited`;case`endpoint-missing`:return`workspace.browseUnsupported`;default:return`workspace.browseLoadFailed`}}function Xm(e){return e===`drive`?`💽`:e===`home`?`🏠`:e===`root`?`🗂`:`📁`}function Zm(e){let{container:t,t:n,platform:r=`win32`,platformName:i=``,hostname:a=``,listDirs:o,onSelect:s,onClose:c,canUseNative:l=!1,onUseNative:u}=e,d=document.createElement(`div`);d.className=`wdb-view`,d.hidden=!0,d.innerHTML=`
|
|
759
759
|
<div class="wdb-header">
|
|
760
|
-
<div class="wdb-agent">${
|
|
760
|
+
<div class="wdb-agent">${I(n(`workspace.browseAgentHost`,{platform:i||r,host:a||`-`}))}</div>
|
|
761
761
|
<div class="wdb-purge" hidden></div>
|
|
762
762
|
<div class="wdb-roots"></div>
|
|
763
763
|
</div>
|
|
764
764
|
<div class="wdb-error" hidden></div>
|
|
765
765
|
<div class="wdb-crumbs"></div>
|
|
766
|
-
<div class="wdb-list" role="listbox" tabindex="0" aria-label="${
|
|
766
|
+
<div class="wdb-list" role="listbox" tabindex="0" aria-label="${I(n(`workspace.browseRoots`))}"></div>
|
|
767
767
|
<div class="wdb-footer">
|
|
768
|
-
<button type="button" class="wdb-btn wdb-back">${
|
|
768
|
+
<button type="button" class="wdb-btn wdb-back">${I(n(`workspace.browseBackToList`))}</button>
|
|
769
769
|
<span class="wdb-spacer"></span>
|
|
770
|
-
<button type="button" class="wdb-btn wdb-native" ${l?``:`hidden`}>${
|
|
771
|
-
<button type="button" class="wdb-btn wdb-choose" disabled>${
|
|
772
|
-
</div>`,t.appendChild(d);let f={roots:d.querySelector(`.wdb-roots`),error:d.querySelector(`.wdb-error`),crumbs:d.querySelector(`.wdb-crumbs`),list:d.querySelector(`.wdb-list`),back:d.querySelector(`.wdb-back`),native:d.querySelector(`.wdb-native`),choose:d.querySelector(`.wdb-choose`)},p={currentPath:null,parent:null,roots:[],entries:[],selectedPath:null,selectedIndex:-1,truncated:!1,loading:!1,outdated:!1,errorText:``,reqSeq:0},m=null;function h(){return Array.from(f.list.querySelectorAll(`.wdb-item`))}function g(){if(!p.roots.length){f.roots.innerHTML=``;return}f.roots.innerHTML=`<span class="wdb-roots-label">${P(n(`workspace.browseRoots`))}</span>`+p.roots.map(e=>`<button type="button" class="wdb-root" data-path="${P(e.path)}" title="${P(e.path)}">${Xm(e.kind)} ${P(e.name)}</button>`).join(``)}function _(){if(!p.currentPath){f.crumbs.innerHTML=``;return}let e=Jm(p.currentPath,r);f.crumbs.innerHTML=e.map((t,n)=>{let r=n===e.length-1;return`<button type="button" class="wdb-crumb${r?` current`:``}" data-path="${P(t.path)}" title="${P(t.path)}"${r?` disabled`:``}>${P(t.name)}</button>`}).join(`<span class="wdb-crumb-sep">›</span>`)}function v(){if(p.outdated){f.list.innerHTML=`<div class="wdb-state">${P(n(`workspace.browseUnsupported`))}</div>`;return}if(p.loading){f.list.innerHTML=`<div class="wdb-state">${P(n(`workspace.browseLoading`))}</div>`;return}let e=!p.currentPath,t=e?p.roots.map(e=>({name:e.name,path:e.path,kind:e.kind,link:!1})):p.entries;if(!t.length){f.list.innerHTML=`<div class="wdb-state">${P(n(`workspace.browseEmpty`))}</div>`;return}f.list.innerHTML=t.map(t=>{let r=p.selectedPath&&t.path===p.selectedPath,i=e?Xm(t.kind):`📁`,a=t.link?`<span class="wdb-link">${P(n(`workspace.browseLinkTag`))}</span>`:``,o=e?``:`<span class="wdb-pick" role="button" data-pick="1" title="${P(n(`workspace.browseChooseDir`))}" aria-label="${P(n(`workspace.browseChooseDir`))}">✓</span>`;return`<button type="button" class="wdb-item${r?` selected`:``}" role="option" aria-selected="${r?`true`:`false`}" data-path="${P(t.path)}" data-root="${e?`1`:`0`}" title="${P(t.path)}"><span class="wdb-item-icon">${i}</span><span class="wdb-item-name">${P(t.name)}</span>${a}${o}</button>`}).join(``),p.truncated&&f.list.insertAdjacentHTML(`beforeend`,`<div class="wdb-state wdb-truncated">${P(n(`workspace.browseTruncated`))}</div>`)}function y(){if(p.selectedPath){f.choose.disabled=!1,f.choose.textContent=n(`workspace.browseChooseDir`);return}f.choose.disabled=!p.currentPath,f.choose.textContent=n(`workspace.browseChooseCurrent`)}function b(){if(!p.errorText){f.error.hidden=!0,f.error.textContent=``;return}f.error.hidden=!1,f.error.textContent=p.errorText}function x(){g(),_(),v(),y(),b()}function S(e,t){p.selectedPath=e,p.selectedIndex=t,h().forEach(t=>{let n=t.dataset.path===e;t.classList.toggle(`selected`,n),t.setAttribute(`aria-selected`,n?`true`:`false`)}),y()}async function C(e){let t=++p.reqSeq;m=null,p.loading=!0,p.errorText=``,x();let r=await o(e||``);if(!(t!==p.reqSeq||d.hidden)){if(p.loading=!1,!r||r.success!==!0){if(r&&r.outdated)p.outdated=!0,p.errorText=n(`workspace.browseUnsupported`);else{let e=r&&r.error?r.error:`unknown`;p.errorText=r&&typeof r.message==`string`&&r.message?r.message:n(Ym(e),{error:r&&r.message?r.message:e})}x();return}p.outdated=!1,p.currentPath=r.path||null,p.parent=r.parent||null,p.roots=Array.isArray(r.roots)?r.roots:[],p.entries=Array.isArray(r.entries)?r.entries:[],p.truncated=!!r.truncated,p.selectedPath=null,p.selectedIndex=-1,x(),f.list.scrollTop=0}}f.roots.addEventListener(`click`,e=>{let t=e.target.closest(`.wdb-root`);t&&C(t.dataset.path)}),f.crumbs.addEventListener(`click`,e=>{let t=e.target.closest(`.wdb-crumb`);!t||t.disabled||C(t.dataset.path)}),f.list.addEventListener(`click`,e=>{let t=e.detail>=2,n=e.target.closest(`.wdb-pick`);if(n){let e=n.closest(`.wdb-item`);e&&w(e.dataset.path);return}let r=e.target.closest(`.wdb-item`);if(r){if(r.dataset.root===`1`){if(t)return;m=null,C(r.dataset.path);return}S(r.dataset.path,h().indexOf(r)),t||(m={path:r.dataset.path,at:Date.now()})}}),f.list.addEventListener(`dblclick`,e=>{if(e.target.closest(`.wdb-pick`))return;let t=e.target.closest(`.wdb-item`);t&&(!m||m.path!==t.dataset.path||Date.now()-m.at>600||C(t.dataset.path))}),f.list.addEventListener(`keydown`,e=>{if(!(p.loading||p.outdated)){if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=h();if(!t.length)return;e.preventDefault();let n=e.key===`ArrowDown`?1:-1,r=Math.min(t.length-1,Math.max(0,p.selectedIndex+n));S(t[r].dataset.path,r),t[r].scrollIntoView({block:`nearest`});return}if(e.key===`Enter`){e.preventDefault();let t=h(),n=p.selectedIndex>=0?t[p.selectedIndex]:null;n&&C(n.dataset.path);return}e.key===`Backspace`&&(e.preventDefault(),p.parent&&C(p.parent))}}),f.list.addEventListener(`mousedown`,()=>{setTimeout(()=>f.list.focus(),0)}),f.back.addEventListener(`click`,()=>E()),f.native.addEventListener(`click`,()=>{typeof u==`function`&&u(),E()});function w(e){e&&(typeof s==`function`&&s(e),E())}f.choose.addEventListener(`click`,()=>{w(p.selectedPath||p.currentPath)});function T(e){p.outdated=!1,p.errorText=``,p.selectedPath=null,p.selectedIndex=-1,d.hidden=!1,C(e||``),setTimeout(()=>f.list.focus(),0)}function E(){d.hidden||(m=null,p.reqSeq+=1,d.hidden=!0,typeof c==`function`&&c())}function D(){p.reqSeq+=1,d.remove()}return{element:d,open:T,close:E,destroy:D,isOpen:()=>!d.hidden}}function Qm(e){let t=e||C.activeSessionId;return t?!!(C.generatingSessionIds?.has(t)||fr(t)>0):!1}n(`zh`,{imageHelper:{uploadToAgentTitle:`上传文件到Agent工作目录,大模型通过工具直接操作`,uploadAndExtractTitle:`上传文件并提取文本内容(支持PDF/Word/Excel/文本等)`,clickToEnlarge:`点击查看大图`,removeImage:`移除图片`,enableImageInputFirst:`请先开启图片输入功能`,screenshotSuccess:`截图成功`,screenshotFailed:`截图失败,请重试`,noActiveTab:`无法获取当前标签页`,cropFailed:`裁剪失败,请重试`,regionScreenshotFailed:`区域截图失败,请确保页面已加载且未被浏览器限制`,imageLoadFailed:`图片加载失败`,screenshotProcessFailed:`截图处理失败,请重试`}}),n(`en`,{imageHelper:{uploadToAgentTitle:`Upload files to Agent workspace; the model operates on them directly via tools`,uploadAndExtractTitle:`Upload files and extract text content (supports PDF/Word/Excel/text, etc.)`,clickToEnlarge:`Click to enlarge`,removeImage:`Remove image`,enableImageInputFirst:`Please enable image input first`,screenshotSuccess:`Screenshot captured`,screenshotFailed:`Screenshot failed, please retry`,noActiveTab:`Unable to get the current tab`,cropFailed:`Cropping failed, please retry`,regionScreenshotFailed:`Region screenshot failed. Make sure the page is loaded and not restricted by the browser.`,imageLoadFailed:`Image load failed`,screenshotProcessFailed:`Screenshot processing failed, please retry`}});function $m(){let e=document.getElementById(`imagePreviewBar`),t=document.getElementById(`screenshotBtn`);e&&(e.style.display=C.attachedImages.length>0?``:`none`),t&&(C.enableImageInput?t.style.removeProperty(`display`):t.style.display=`none`),eh(),C.enableImageInput||(C.attachedImages=[]),nh()}function eh(){let e=document.getElementById(`userInput`);e&&e.style.removeProperty(`padding-right`)}function th(){let e=document.getElementById(`fileAttachBtn`),t=document.getElementById(`fileInput`);e&&(e.style.display=C.enableFileInput?``:`none`),t&&(C.agentPlatform?.connected?(t.accept=`*`,e&&(e.title=r(`imageHelper.uploadToAgentTitle`))):(t.accept=`.pdf,.docx,.xlsx,.xls,.txt,.md,.json,.js,.jsx,.ts,.tsx,.html,.css,.scss,.less,.xml,.yaml,.yml,.py,.java,.c,.cpp,.h,.go,.rs,.rb,.php,.sql,.sh,.bash,.zsh,.cfg,.ini,.toml,.conf,.log,.csv,.tsv,.env,.vue,.svelte,.astro,.rtf`,e&&(e.title=r(`imageHelper.uploadAndExtractTitle`)))),eh(),C.enableFileInput||km()}function nh(){document.dispatchEvent(new CustomEvent(`input-attachments-changed`));let e=document.getElementById(`imagePreviewBar`);if(e){if(e.innerHTML=``,C.attachedImages.length===0){e.style.display=`none`;return}e.style.display=``,C.attachedImages.forEach((t,n)=>{let i=document.createElement(`div`);i.className=`image-preview-item`;let a=document.createElement(`img`);a.src=t.dataUrl||t.compressedUrl||t.originalUrl,a.className=`image-preview-thumb`,a.title=r(`imageHelper.clickToEnlarge`),a.style.cursor=`zoom-in`,a.addEventListener(`click`,()=>{Mp(t.originalUrl||t.dataUrl||t.compressedUrl,a)});let o=document.createElement(`button`);o.className=`image-preview-remove`,o.innerHTML=`×`,o.title=r(`imageHelper.removeImage`),o.addEventListener(`click`,e=>{e.stopPropagation(),C.attachedImages.splice(n,1),nh()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}async function rh(){if(!C.enableImageInput){F(r(`imageHelper.enableImageInputFirst`));return}try{let e=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});e?.dataUrl&&(Bp(await(await fetch(e.dataUrl)).blob()),F(r(`imageHelper.screenshotSuccess`)))}catch(e){i.error(`[SidePanel] full page screenshot failed:`,e),F(r(`imageHelper.screenshotFailed`))}}async function ih(){let e=await Ie();if(!e){F(r(`imageHelper.noActiveTab`));return}try{let t=await chrome.tabs.sendMessage(e,{type:`START_REGION_SELECTION`});if(!t)return;i.debug(`[SidePanel] regionselectresult:`,t);let n=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});if(!n?.dataUrl){F(r(`imageHelper.screenshotFailed`));return}let a=await ah(n.dataUrl,t);if(!a){F(r(`imageHelper.cropFailed`));return}Bp(await(await fetch(a)).blob())}catch(e){i.error(`[SidePanel] region screenshot failed:`,e),F(r(`imageHelper.regionScreenshotFailed`))}}function ah(e,t){return new Promise((n,i)=>{let a=new Image;a.onload=()=>{let e=document.createElement(`canvas`),r=window.devicePixelRatio||1,i=t.x*r,o=t.y*r,s=t.width*r,c=t.height*r;e.width=s,e.height=c,e.getContext(`2d`,{willReadFrequently:!0}).drawImage(a,i,o,s,c,0,0,s,c),n(e.toDataURL(`image/jpeg`,.85))},a.onerror=()=>i(Error(r(`imageHelper.imageLoadFailed`))),a.src=e})}async function oh(e,t,n){if(!C.enableImageInput){F(r(`imageHelper.enableImageInputFirst`));return}try{let i=e;t===`region`&&n&&(i=await ah(e,n)),Bp(await(await fetch(i)).blob()),F(r(`imageHelper.screenshotSuccess`))}catch(e){i.error(`[SidePanel] pageshortcutscreenshotprocessing failed:`,e),F(r(`imageHelper.screenshotProcessFailed`))}}var sh=t({attachFilesForQuestion:()=>gy,closePreview:()=>Q_,closeWorkspacePanel:()=>Bv,closeWorkspacePreview:()=>zv,initWorkspacePanel:()=>Ah,locateFileInWorkspace:()=>Lv,openWorkspacePanel:()=>Zh,previewArtifactFile:()=>Rv,refreshWorkspacePanel:()=>Av,resetAndRefreshWorkspace:()=>jv,resolveWorkspaceAbsolutePath:()=>Vv,showSwitchWorkdirDialog:()=>iy,updateWorkspacePanelVisibility:()=>Mv});n(`zh`,{workspace:{workDir:`工作目录`,closePanel:`关闭面板`,embedMode:`嵌入模式`,floatMode:`浮窗模式`,openPanel:`打开工作目录面板`,narrowViewportHint:`视口过窄,已切回浮窗模式`,switchWorkdir:`切换工作目录`,backToParent:`返回上级目录`,uploadToCurrent:`上传文件到当前目录`,newFolder:`新建文件夹`,askSelectedFiles:`基于选中的文件进行问答`,downloadSelected:`下载选中的文件/目录(多选打包为ZIP)`,deleteSelected:`删除选中的文件`,clearSearch:`清除`,search:`搜索`,searchPlaceholder:`搜索...`,selectAllToggle:`全选/取消全选`,colName:`文件名`,colSize:`大小`,colTime:`修改时间`,noMatch:`未找到匹配的文件`,dirEmpty:`此目录为空`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,loadDirFailed:`加载目录失败`,refreshFailed:`无法刷新,请确认 Agent 已连接`,agentNotConnected:`Agent 未连接`,agentNotConnectedUpload:`Agent 未连接,无法上传`,unsupportedFileType:`不支持的文件类型`,binaryFileNoPreview:`疑似二进制文件,不支持文本预览,请直接下载`,unknownError:`未知错误`,copiedFileName:`已复制文件名: {name}`,copiedPath:`已复制路径: {path}`,copyFailed:`复制失败`,copiedToClipboard:`已复制到剪贴板`,copyFailedManual:`复制失败,请手动选择复制`,getContentFailed:`获取内容失败`,codeCopiedToClipboard:`代码已复制到剪贴板`,copyUnsupportedType:`此文件类型不支持复制文本内容`,copiedToClipboardShort:`已复制到剪贴板`,clickToCopy:`点击复制`,preview:`预览`,previewBtn:`预览`,details:`详情`,download:`下载`,downloadFile:`下载文件`,rename:`重命名`,askFile:`基于文件问答`,delete:`删除`,copyAll:`复制`,copyAllTitle:`复制全部内容`,toggleRenderPreview:`切换渲染预览`,openInBrowser:`在浏览器中打开`,openInBrowserBtn:`在浏览器中打开`,fullscreenPreview:`全屏预览`,exitFullscreen:`退出全屏`,enterEditMode:`进入编辑模式`,edit:`编辑`,save:`保存`,saveChanges:`保存修改 (Ctrl+S)`,cancelChanges:`取消修改 (Esc)`,closePreview:`关闭预览`,close:`关闭`,confirm:`确定`,cancel:`取消`,switchToSourcePreview:`切换为源码预览`,switchToRenderPreview:`切换为渲染预览`,markdownRendered:`Markdown 渲染`,lineCount:`{count} 行`,linesModified:`{count} 行 · 已修改`,truncatedHint:`(仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容)`,fileTooLargeNoPreview:`文件过大 ({size}),不支持预览,请直接下载`,fileTooLargeOpenInBrowser:`文件过大 ({size}),无法内置预览,请点击上方「在浏览器中打开」按钮查看`,previewFailed:`预览失败: {error}`,openFailed:`打开失败: {error}`,documentEmpty:`(文档为空)`,pptxEmptyOrFailed:`PPTX 文件为空或解析失败`,pageCount:`{count} 页`,prevPage:`上一页`,nextPage:`下一页`,zoomOut:`缩小`,zoomIn:`放大`,fitPage:`适应页面`,originalSize:`原始大小`,imageLoadFailed:`图片加载失败`,parsingExcel:`正在解析 Excel 文件...`,loadingData:`正在加载数据...`,requestFailed:`请求失败: {error}`,parseFailed:`解析失败: {error}`,noSheetsInWorkbook:`工作簿中没有工作表`,sheetNotFound:`未找到工作表数据`,emptySheet:`(空工作表)`,xlsxTruncatedHint:`仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容`,unsupportedMediaHint:`⚠ 浏览器不支持播放此格式({ext}),请下载后使用本地播放器查看。`,uploading:`上传中...`,downloadInProgress:`下载中`,uploadInProgress:`上传中`,cancelUpload:`取消上传`,downloadCanceled:`下载已取消`,downloadFailed:`下载失败`,downloadFailedWithError:`下载失败: {error}`,savingToLocal:`正在由浏览器保存至本地...`,savedToLocal:`已保存至本地`,downloaded:`已下载: {name}`,downloadedCount:`已下载 {count} 个文件`,downloadedZip:`已下载 {count} 个文件(ZIP 压缩包)`,fileCount:`{count} 个文件`,uploadCanceled:`已取消上传`,uploadSuccessCount:`成功 {count}`,uploadSkippedCount:`跳过 {count}`,uploadFailedCount:`失败 {count}`,uploadComplete:`上传完成`,uploadCompleteWithStats:`上传完成 · {stats}`,uploadedFiles:`成功上传 {count} 个文件`,filesSkipped:`{count} 个文件已存在,跳过上传`,filesUploadFailed:`{count} 个文件上传失败`,uploadFailed:`上传失败`,uploadFailedWithStatus:`上传失败 ({status})`,parseResponseFailed:`解析响应失败`,networkError:`网络错误`,cannotMoveToSubdir:`不能将目录移动到其子目录中`,moving:`移动中...`,movedToDir:`"{name}" 已移动到目标目录`,movedToTarget:`"{name}" 已移动到 "{target}"`,moveFailed:`移动失败: {error}`,searching:`搜索中...`,confirmDeleteDir:`确定要删除目录 "{name}" 及其所有内容吗?
|
|
770
|
+
<button type="button" class="wdb-btn wdb-native" ${l?``:`hidden`}>${I(n(`workspace.browseUseNative`))}</button>
|
|
771
|
+
<button type="button" class="wdb-btn wdb-choose" disabled>${I(n(`workspace.browseChooseCurrent`))}</button>
|
|
772
|
+
</div>`,t.appendChild(d);let f={roots:d.querySelector(`.wdb-roots`),error:d.querySelector(`.wdb-error`),crumbs:d.querySelector(`.wdb-crumbs`),list:d.querySelector(`.wdb-list`),back:d.querySelector(`.wdb-back`),native:d.querySelector(`.wdb-native`),choose:d.querySelector(`.wdb-choose`)},p={currentPath:null,parent:null,roots:[],entries:[],selectedPath:null,selectedIndex:-1,truncated:!1,loading:!1,outdated:!1,errorText:``,reqSeq:0},m=null;function h(){return Array.from(f.list.querySelectorAll(`.wdb-item`))}function g(){if(!p.roots.length){f.roots.innerHTML=``;return}f.roots.innerHTML=`<span class="wdb-roots-label">${I(n(`workspace.browseRoots`))}</span>`+p.roots.map(e=>`<button type="button" class="wdb-root" data-path="${I(e.path)}" title="${I(e.path)}">${Xm(e.kind)} ${I(e.name)}</button>`).join(``)}function _(){if(!p.currentPath){f.crumbs.innerHTML=``;return}let e=Jm(p.currentPath,r);f.crumbs.innerHTML=e.map((t,n)=>{let r=n===e.length-1;return`<button type="button" class="wdb-crumb${r?` current`:``}" data-path="${I(t.path)}" title="${I(t.path)}"${r?` disabled`:``}>${I(t.name)}</button>`}).join(`<span class="wdb-crumb-sep">›</span>`)}function v(){if(p.outdated){f.list.innerHTML=`<div class="wdb-state">${I(n(`workspace.browseUnsupported`))}</div>`;return}if(p.loading){f.list.innerHTML=`<div class="wdb-state">${I(n(`workspace.browseLoading`))}</div>`;return}let e=!p.currentPath,t=e?p.roots.map(e=>({name:e.name,path:e.path,kind:e.kind,link:!1})):p.entries;if(!t.length){f.list.innerHTML=`<div class="wdb-state">${I(n(`workspace.browseEmpty`))}</div>`;return}f.list.innerHTML=t.map(t=>{let r=p.selectedPath&&t.path===p.selectedPath,i=e?Xm(t.kind):`📁`,a=t.link?`<span class="wdb-link">${I(n(`workspace.browseLinkTag`))}</span>`:``,o=e?``:`<span class="wdb-pick" role="button" data-pick="1" title="${I(n(`workspace.browseChooseDir`))}" aria-label="${I(n(`workspace.browseChooseDir`))}">✓</span>`;return`<button type="button" class="wdb-item${r?` selected`:``}" role="option" aria-selected="${r?`true`:`false`}" data-path="${I(t.path)}" data-root="${e?`1`:`0`}" title="${I(t.path)}"><span class="wdb-item-icon">${i}</span><span class="wdb-item-name">${I(t.name)}</span>${a}${o}</button>`}).join(``),p.truncated&&f.list.insertAdjacentHTML(`beforeend`,`<div class="wdb-state wdb-truncated">${I(n(`workspace.browseTruncated`))}</div>`)}function y(){if(p.selectedPath){f.choose.disabled=!1,f.choose.textContent=n(`workspace.browseChooseDir`);return}f.choose.disabled=!p.currentPath,f.choose.textContent=n(`workspace.browseChooseCurrent`)}function b(){if(!p.errorText){f.error.hidden=!0,f.error.textContent=``;return}f.error.hidden=!1,f.error.textContent=p.errorText}function x(){g(),_(),v(),y(),b()}function S(e,t){p.selectedPath=e,p.selectedIndex=t,h().forEach(t=>{let n=t.dataset.path===e;t.classList.toggle(`selected`,n),t.setAttribute(`aria-selected`,n?`true`:`false`)}),y()}async function C(e){let t=++p.reqSeq;m=null,p.loading=!0,p.errorText=``,x();let r=await o(e||``);if(!(t!==p.reqSeq||d.hidden)){if(p.loading=!1,!r||r.success!==!0){if(r&&r.outdated)p.outdated=!0,p.errorText=n(`workspace.browseUnsupported`);else{let e=r&&r.error?r.error:`unknown`;p.errorText=r&&typeof r.message==`string`&&r.message?r.message:n(Ym(e),{error:r&&r.message?r.message:e})}x();return}p.outdated=!1,p.currentPath=r.path||null,p.parent=r.parent||null,p.roots=Array.isArray(r.roots)?r.roots:[],p.entries=Array.isArray(r.entries)?r.entries:[],p.truncated=!!r.truncated,p.selectedPath=null,p.selectedIndex=-1,x(),f.list.scrollTop=0}}f.roots.addEventListener(`click`,e=>{let t=e.target.closest(`.wdb-root`);t&&C(t.dataset.path)}),f.crumbs.addEventListener(`click`,e=>{let t=e.target.closest(`.wdb-crumb`);!t||t.disabled||C(t.dataset.path)}),f.list.addEventListener(`click`,e=>{let t=e.detail>=2,n=e.target.closest(`.wdb-pick`);if(n){let e=n.closest(`.wdb-item`);e&&w(e.dataset.path);return}let r=e.target.closest(`.wdb-item`);if(r){if(r.dataset.root===`1`){if(t)return;m=null,C(r.dataset.path);return}S(r.dataset.path,h().indexOf(r)),t||(m={path:r.dataset.path,at:Date.now()})}}),f.list.addEventListener(`dblclick`,e=>{if(e.target.closest(`.wdb-pick`))return;let t=e.target.closest(`.wdb-item`);t&&(!m||m.path!==t.dataset.path||Date.now()-m.at>600||C(t.dataset.path))}),f.list.addEventListener(`keydown`,e=>{if(!(p.loading||p.outdated)){if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=h();if(!t.length)return;e.preventDefault();let n=e.key===`ArrowDown`?1:-1,r=Math.min(t.length-1,Math.max(0,p.selectedIndex+n));S(t[r].dataset.path,r),t[r].scrollIntoView({block:`nearest`});return}if(e.key===`Enter`){e.preventDefault();let t=h(),n=p.selectedIndex>=0?t[p.selectedIndex]:null;n&&C(n.dataset.path);return}e.key===`Backspace`&&(e.preventDefault(),p.parent&&C(p.parent))}}),f.list.addEventListener(`mousedown`,()=>{setTimeout(()=>f.list.focus(),0)}),f.back.addEventListener(`click`,()=>E()),f.native.addEventListener(`click`,()=>{typeof u==`function`&&u(),E()});function w(e){e&&(typeof s==`function`&&s(e),E())}f.choose.addEventListener(`click`,()=>{w(p.selectedPath||p.currentPath)});function T(e){p.outdated=!1,p.errorText=``,p.selectedPath=null,p.selectedIndex=-1,d.hidden=!1,C(e||``),setTimeout(()=>f.list.focus(),0)}function E(){d.hidden||(m=null,p.reqSeq+=1,d.hidden=!0,typeof c==`function`&&c())}function D(){p.reqSeq+=1,d.remove()}return{element:d,open:T,close:E,destroy:D,isOpen:()=>!d.hidden}}function Qm(e){let t=e||C.activeSessionId;return t?!!(C.generatingSessionIds?.has(t)||fr(t)>0):!1}n(`zh`,{imageHelper:{uploadToAgentTitle:`上传文件到Agent工作目录,大模型通过工具直接操作`,uploadAndExtractTitle:`上传文件并提取文本内容(支持PDF/Word/Excel/文本等)`,clickToEnlarge:`点击查看大图`,removeImage:`移除图片`,enableImageInputFirst:`请先开启图片输入功能`,screenshotSuccess:`截图成功`,screenshotFailed:`截图失败,请重试`,noActiveTab:`无法获取当前标签页`,cropFailed:`裁剪失败,请重试`,regionScreenshotFailed:`区域截图失败,请确保页面已加载且未被浏览器限制`,imageLoadFailed:`图片加载失败`,screenshotProcessFailed:`截图处理失败,请重试`}}),n(`en`,{imageHelper:{uploadToAgentTitle:`Upload files to Agent workspace; the model operates on them directly via tools`,uploadAndExtractTitle:`Upload files and extract text content (supports PDF/Word/Excel/text, etc.)`,clickToEnlarge:`Click to enlarge`,removeImage:`Remove image`,enableImageInputFirst:`Please enable image input first`,screenshotSuccess:`Screenshot captured`,screenshotFailed:`Screenshot failed, please retry`,noActiveTab:`Unable to get the current tab`,cropFailed:`Cropping failed, please retry`,regionScreenshotFailed:`Region screenshot failed. Make sure the page is loaded and not restricted by the browser.`,imageLoadFailed:`Image load failed`,screenshotProcessFailed:`Screenshot processing failed, please retry`}});function $m(){let e=document.getElementById(`imagePreviewBar`),t=document.getElementById(`screenshotBtn`);e&&(e.style.display=C.attachedImages.length>0?``:`none`),t&&(C.enableImageInput?t.style.removeProperty(`display`):t.style.display=`none`),eh(),C.enableImageInput||(C.attachedImages=[]),nh()}function eh(){let e=document.getElementById(`userInput`);e&&e.style.removeProperty(`padding-right`)}function th(){let e=document.getElementById(`fileAttachBtn`),t=document.getElementById(`fileInput`);e&&(e.style.display=C.enableFileInput?``:`none`),t&&(C.agentPlatform?.connected?(t.accept=`*`,e&&(e.title=r(`imageHelper.uploadToAgentTitle`))):(t.accept=`.pdf,.docx,.xlsx,.xls,.txt,.md,.json,.js,.jsx,.ts,.tsx,.html,.css,.scss,.less,.xml,.yaml,.yml,.py,.java,.c,.cpp,.h,.go,.rs,.rb,.php,.sql,.sh,.bash,.zsh,.cfg,.ini,.toml,.conf,.log,.csv,.tsv,.env,.vue,.svelte,.astro,.rtf`,e&&(e.title=r(`imageHelper.uploadAndExtractTitle`)))),eh(),C.enableFileInput||km()}function nh(){document.dispatchEvent(new CustomEvent(`input-attachments-changed`));let e=document.getElementById(`imagePreviewBar`);if(e){if(e.innerHTML=``,C.attachedImages.length===0){e.style.display=`none`;return}e.style.display=``,C.attachedImages.forEach((t,n)=>{let i=document.createElement(`div`);i.className=`image-preview-item`;let a=document.createElement(`img`);a.src=t.dataUrl||t.compressedUrl||t.originalUrl,a.className=`image-preview-thumb`,a.title=r(`imageHelper.clickToEnlarge`),a.style.cursor=`zoom-in`,a.addEventListener(`click`,()=>{Mp(t.originalUrl||t.dataUrl||t.compressedUrl,a)});let o=document.createElement(`button`);o.className=`image-preview-remove`,o.innerHTML=`×`,o.title=r(`imageHelper.removeImage`),o.addEventListener(`click`,e=>{e.stopPropagation(),C.attachedImages.splice(n,1),nh()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}async function rh(){if(!C.enableImageInput){P(r(`imageHelper.enableImageInputFirst`));return}try{let e=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});e?.dataUrl&&(Bp(await(await fetch(e.dataUrl)).blob()),P(r(`imageHelper.screenshotSuccess`)))}catch(e){i.error(`[SidePanel] full page screenshot failed:`,e),P(r(`imageHelper.screenshotFailed`))}}async function ih(){let e=await Ke();if(!e){P(r(`imageHelper.noActiveTab`));return}try{let t=await chrome.tabs.sendMessage(e,{type:`START_REGION_SELECTION`});if(!t)return;i.debug(`[SidePanel] regionselectresult:`,t);let n=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});if(!n?.dataUrl){P(r(`imageHelper.screenshotFailed`));return}let a=await ah(n.dataUrl,t);if(!a){P(r(`imageHelper.cropFailed`));return}Bp(await(await fetch(a)).blob())}catch(e){i.error(`[SidePanel] region screenshot failed:`,e),P(r(`imageHelper.regionScreenshotFailed`))}}function ah(e,t){return new Promise((n,i)=>{let a=new Image;a.onload=()=>{let e=document.createElement(`canvas`),r=window.devicePixelRatio||1,i=t.x*r,o=t.y*r,s=t.width*r,c=t.height*r;e.width=s,e.height=c,e.getContext(`2d`,{willReadFrequently:!0}).drawImage(a,i,o,s,c,0,0,s,c),n(e.toDataURL(`image/jpeg`,.85))},a.onerror=()=>i(Error(r(`imageHelper.imageLoadFailed`))),a.src=e})}async function oh(e,t,n){if(!C.enableImageInput){P(r(`imageHelper.enableImageInputFirst`));return}try{let i=e;t===`region`&&n&&(i=await ah(e,n)),Bp(await(await fetch(i)).blob()),P(r(`imageHelper.screenshotSuccess`))}catch(e){i.error(`[SidePanel] pageshortcutscreenshotprocessing failed:`,e),P(r(`imageHelper.screenshotProcessFailed`))}}var sh=t({attachFilesForQuestion:()=>gy,closePreview:()=>Q_,closeWorkspacePanel:()=>Bv,closeWorkspacePreview:()=>zv,initWorkspacePanel:()=>Ah,locateFileInWorkspace:()=>Lv,openWorkspacePanel:()=>Zh,previewArtifactFile:()=>Rv,refreshWorkspacePanel:()=>Av,resetAndRefreshWorkspace:()=>jv,resolveWorkspaceAbsolutePath:()=>Vv,showSwitchWorkdirDialog:()=>iy,updateWorkspacePanelVisibility:()=>Mv});n(`zh`,{workspace:{workDir:`工作目录`,closePanel:`关闭面板`,embedMode:`嵌入模式`,floatMode:`浮窗模式`,openPanel:`打开工作目录面板`,narrowViewportHint:`视口过窄,已切回浮窗模式`,switchWorkdir:`切换工作目录`,backToParent:`返回上级目录`,uploadToCurrent:`上传文件到当前目录`,newFolder:`新建文件夹`,askSelectedFiles:`基于选中的文件进行问答`,downloadSelected:`下载选中的文件/目录(多选打包为ZIP)`,deleteSelected:`删除选中的文件`,clearSearch:`清除`,search:`搜索`,searchPlaceholder:`搜索...`,selectAllToggle:`全选/取消全选`,colName:`文件名`,colSize:`大小`,colTime:`修改时间`,noMatch:`未找到匹配的文件`,dirEmpty:`此目录为空`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,loadDirFailed:`加载目录失败`,refreshFailed:`无法刷新,请确认 Agent 已连接`,agentNotConnected:`Agent 未连接`,agentNotConnectedUpload:`Agent 未连接,无法上传`,unsupportedFileType:`不支持的文件类型`,binaryFileNoPreview:`疑似二进制文件,不支持文本预览,请直接下载`,unknownError:`未知错误`,copiedFileName:`已复制文件名: {name}`,copiedPath:`已复制路径: {path}`,copyFailed:`复制失败`,copiedToClipboard:`已复制到剪贴板`,copyFailedManual:`复制失败,请手动选择复制`,getContentFailed:`获取内容失败`,codeCopiedToClipboard:`代码已复制到剪贴板`,copyUnsupportedType:`此文件类型不支持复制文本内容`,copiedToClipboardShort:`已复制到剪贴板`,clickToCopy:`点击复制`,preview:`预览`,previewBtn:`预览`,details:`详情`,download:`下载`,downloadFile:`下载文件`,rename:`重命名`,askFile:`基于文件问答`,delete:`删除`,copyAll:`复制`,copyAllTitle:`复制全部内容`,toggleRenderPreview:`切换渲染预览`,openInBrowser:`在浏览器中打开`,openInBrowserBtn:`在浏览器中打开`,fullscreenPreview:`全屏预览`,exitFullscreen:`退出全屏`,enterEditMode:`进入编辑模式`,edit:`编辑`,save:`保存`,saveChanges:`保存修改 (Ctrl+S)`,cancelChanges:`取消修改 (Esc)`,closePreview:`关闭预览`,close:`关闭`,confirm:`确定`,cancel:`取消`,switchToSourcePreview:`切换为源码预览`,switchToRenderPreview:`切换为渲染预览`,markdownRendered:`Markdown 渲染`,lineCount:`{count} 行`,linesModified:`{count} 行 · 已修改`,truncatedHint:`(仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容)`,fileTooLargeNoPreview:`文件过大 ({size}),不支持预览,请直接下载`,fileTooLargeOpenInBrowser:`文件过大 ({size}),无法内置预览,请点击上方「在浏览器中打开」按钮查看`,previewFailed:`预览失败: {error}`,openFailed:`打开失败: {error}`,documentEmpty:`(文档为空)`,pptxEmptyOrFailed:`PPTX 文件为空或解析失败`,pageCount:`{count} 页`,prevPage:`上一页`,nextPage:`下一页`,zoomOut:`缩小`,zoomIn:`放大`,fitPage:`适应页面`,originalSize:`原始大小`,imageLoadFailed:`图片加载失败`,parsingExcel:`正在解析 Excel 文件...`,loadingData:`正在加载数据...`,requestFailed:`请求失败: {error}`,parseFailed:`解析失败: {error}`,noSheetsInWorkbook:`工作簿中没有工作表`,sheetNotFound:`未找到工作表数据`,emptySheet:`(空工作表)`,xlsxTruncatedHint:`仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容`,unsupportedMediaHint:`⚠ 浏览器不支持播放此格式({ext}),请下载后使用本地播放器查看。`,uploading:`上传中...`,downloadInProgress:`下载中`,uploadInProgress:`上传中`,cancelUpload:`取消上传`,downloadCanceled:`下载已取消`,downloadFailed:`下载失败`,downloadFailedWithError:`下载失败: {error}`,savingToLocal:`正在由浏览器保存至本地...`,savedToLocal:`已保存至本地`,downloaded:`已下载: {name}`,downloadedCount:`已下载 {count} 个文件`,downloadedZip:`已下载 {count} 个文件(ZIP 压缩包)`,fileCount:`{count} 个文件`,uploadCanceled:`已取消上传`,uploadSuccessCount:`成功 {count}`,uploadSkippedCount:`跳过 {count}`,uploadFailedCount:`失败 {count}`,uploadComplete:`上传完成`,uploadCompleteWithStats:`上传完成 · {stats}`,uploadedFiles:`成功上传 {count} 个文件`,filesSkipped:`{count} 个文件已存在,跳过上传`,filesUploadFailed:`{count} 个文件上传失败`,uploadFailed:`上传失败`,uploadFailedWithStatus:`上传失败 ({status})`,parseResponseFailed:`解析响应失败`,networkError:`网络错误`,cannotMoveToSubdir:`不能将目录移动到其子目录中`,moving:`移动中...`,movedToDir:`"{name}" 已移动到目标目录`,movedToTarget:`"{name}" 已移动到 "{target}"`,moveFailed:`移动失败: {error}`,searching:`搜索中...`,confirmDeleteDir:`确定要删除目录 "{name}" 及其所有内容吗?
|
|
773
773
|
|
|
774
774
|
路径: {path}
|
|
775
775
|
类型: 目录
|
|
@@ -1014,7 +1014,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1014
1014
|
<div class="workspace-preview-rail" id="workspacePreviewRail"></div>
|
|
1015
1015
|
</div>
|
|
1016
1016
|
</div>
|
|
1017
|
-
`,hn(`workspace`).appendChild(e),jh(),document.addEventListener(`session-switched`,()=>{sy().catch(e=>i.warn(`[WorkspacePanel] sync after session switch failed`,e))}),document.addEventListener(`session-workdir-changed`,e=>{let t=e.detail?.sessionId;t&&t!==C.activeSessionId||sy().catch(e=>i.warn(`[WorkspacePanel] sync after workdir change failed`,e))}),document.addEventListener(`session-hydrated`,()=>{sy().catch(e=>i.warn(`[WorkspacePanel] sync after session hydrated failed`,e))}),Jv(),Sv(),Gh(),Kh(),Yh(),i.debug(`[WorkspacePanel] workspace panelinitializing`)}function jh(){document.getElementById(`workspacePanelContainer`);let e=document.getElementById(`workspacePanel`);document.getElementById(`workspacePanelToggle`).addEventListener(`click`,async t=>{t.stopPropagation(),e.classList.contains(`expanded`)?Qh():await Zh()}),document.getElementById(`workspacePanelClose`).addEventListener(`click`,e=>{e.stopPropagation(),Qh()}),document.getElementById(`workspacePanelModeBtn`).addEventListener(`click`,async e=>{e.stopPropagation(),await Wh()});let t=document.getElementById(`workspaceSwitchBtn`);t&&t.addEventListener(`click`,async e=>{e.stopPropagation(),await iy()}),document.getElementById(`workspaceBackBtn`).addEventListener(`click`,e=>{e.stopPropagation(),wv()}),document.getElementById(`workspaceRefreshBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Tv()}),document.getElementById(`workspaceUploadBtn`).addEventListener(`click`,e=>{e.stopPropagation(),cv()}),document.getElementById(`workspaceNewFolderBtn`).addEventListener(`click`,e=>{e.stopPropagation(),my()}),document.getElementById(`workspaceAskBtn`).addEventListener(`click`,e=>{e.stopPropagation(),_y()}),document.getElementById(`workspaceDownloadDirBtn`).addEventListener(`click`,e=>{e.stopPropagation(),ov()}),document.getElementById(`workspaceBatchDeleteBtn`).addEventListener(`click`,e=>{e.stopPropagation(),ey()});let n=document.getElementById(`workspaceSearchInput`),i=document.getElementById(`workspaceToolbar`),a=i.querySelector(`.workspace-search-box`);function o(){return i.clientWidth<188}function s(){n.value.trim()?(a.classList.add(`search-box-expanded`),o()&&i.classList.add(`search-focused`)):(a.classList.remove(`search-box-expanded`),i.classList.remove(`search-focused`))}n.addEventListener(`input`,e=>{Xv(e),s()}),n.addEventListener(`focus`,()=>{o()&&i.classList.add(`search-focused`)}),n.addEventListener(`blur`,()=>{n.value.trim()||i.classList.remove(`search-focused`)}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`)e.stopPropagation(),Zv();else if(e.key===`Escape`)e.stopPropagation(),Qv();else if(e.key===`ArrowUp`){if(e.preventDefault(),Kv.length===0)return;qv===-1?qv=Kv.length-1:qv>0&&qv--,n.value=Kv[qv],Uv=n.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=Uv?``:`none`}else e.key===`ArrowDown`&&(e.preventDefault(),qv===-1||qv>=Kv.length-1?(qv=-1,n.value=``,Uv=``,document.getElementById(`workspaceSearchClear`).style.display=`none`):(qv++,n.value=Kv[qv],Uv=n.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=Uv?``:`none`))}),document.getElementById(`workspaceSearchBtn`).addEventListener(`click`,()=>{n.focus(),Zv()}),document.getElementById(`workspaceSearchClear`).addEventListener(`click`,Qv),document.getElementById(`workspacePanel`).querySelectorAll(`.workspace-file-header .sortable`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;Ch.field===t?Ch.asc=!Ch.asc:(Ch.field=t,Ch.asc=!0),Og(),gg()})}),document.getElementById(`workspaceSelectAll`).addEventListener(`click`,Eg),document.getElementById(`workspacePanelContent`).addEventListener(`click`,Cg),document.getElementById(`workspacePanelContent`).addEventListener(`dblclick`,wg),document.getElementById(`workspacePanelContent`).addEventListener(`keydown`,Sg),document.getElementById(`workspacePanelContent`).tabIndex=0,document.getElementById(`workspacePanelContent`).addEventListener(`dragstart`,xg);let c=null;document.getElementById(`workspacePanelContent`).addEventListener(`scroll`,()=>{fg&&(c&&cancelAnimationFrame(c),c=requestAnimationFrame(()=>{c=null,document.getElementById(`workspacePanelContent`).scrollTop!==pg&&hg()}))}),document.getElementById(`workspacePreviewClose`).addEventListener(`click`,()=>Q_()),document.getElementById(`workspacePreviewCopyBtn`).addEventListener(`click`,e=>z_(e)),document.getElementById(`workspacePreviewDownloadBtn`).addEventListener(`click`,H_),document.getElementById(`workspacePreviewOpenBrowserBtn`).addEventListener(`click`,U_),document.getElementById(`workspacePreviewFullscreenBtn`).addEventListener(`click`,q_),document.getElementById(`workspacePreviewMdToggleBtn`).addEventListener(`click`,J_),document.getElementById(`workspacePreviewEditBtn`).addEventListener(`click`,$_),document.getElementById(`workspacePreviewSaveBtn`).addEventListener(`click`,ev),document.getElementById(`workspacePreviewCancelBtn`).addEventListener(`click`,tv),O_(),document.addEventListener(`keydown`,iv),document.getElementById(`workspacePreviewFilename`).addEventListener(`click`,async e=>{let t=document.getElementById(`workspacePreviewArea`),n=t.dataset.previewName,i=t.dataset.previewPath;if(n){if((e.ctrlKey||e.metaKey)&&!e.shiftKey){e.preventDefault();try{await navigator.clipboard.writeText(n),F(r(`workspace.copiedFileName`,{name:n}))}catch{F(r(`workspace.copyFailed`),`error`)}}else if((e.ctrlKey||e.metaKey)&&e.shiftKey){if(e.preventDefault(),!i)return;try{await navigator.clipboard.writeText(i),F(r(`workspace.copiedPath`,{path:i}))}catch{F(r(`workspace.copyFailed`),`error`)}}}}),xv(),chrome.storage.local.onChanged.addListener(Cv);let l=document.createElement(`input`);l.type=`file`,l.multiple=!0,l.id=`workspaceFileInput`,l.style.display=`none`,l.addEventListener(`change`,lv),document.body.appendChild(l)}var Mh=[];function Nh(e){lh.push(e),lh.length>uh&&lh.shift()}function Ph(e){if(!e||typeof e!=`string`)return`unnamed`;let t=e.replace(/[<>:"|?*\\/\x00-\x1f]/g,`_`);return t=t.replace(/\.+$/,``),t=t.trim(),t||=`unnamed`,t}function Fh(e,t){let n=Z(e);if(!t)return n;let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return n.replace(RegExp(`(${r})`,`gi`),`<mark class="search-highlight">$1</mark>`)}var Ih=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/></svg>`,Lh=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/><path d="m8 9-3 3 3 3"/></svg>`;function Rh(){let e=document.getElementById(`mainRow`),t=e?e.clientWidth:window.innerWidth;return Math.max(dh,t-fh)}function zh(e){return Math.max(dh,Math.min(e,Rh()))}function Bh(e){let t=document.getElementById(`workspacePanelModeBtn`);t&&(t.title=r(e?`workspace.floatMode`:`workspace.embedMode`),t.innerHTML=e?Lh:Ih)}function Vh(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;let t=document.getElementById(`mainRow`);t&&e.parentElement!==t&&t.appendChild(e),e.classList.add(`embedded`),e.style.setProperty(`--ws-embed-width`,`${yh}px`),Bh(!0)}function Hh(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;e.classList.remove(`embedded`);let t=hn(`workspace`);t&&e.parentElement!==t&&t.appendChild(e),Bh(!1)}async function Uh(){try{await chrome.storage.local.set({[hh]:vh,[gh]:yh})}catch(e){i.warn(`[WorkspacePanel] persist embed state failed`,e)}}async function Wh(){if(vh){vh=!1,xh=!1,bh=!1,Hh(),await Uh();return}let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<ph){F(r(`workspace.narrowViewportHint`),`error`);return}document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await Xh(),yh=zh(yh),Vh(),vh=!0,xh=!0,bh=!1,await Uh()}function Gh(){let e=document.getElementById(`workspacePanelContainer`),t=document.createElement(`div`);t.className=`workspace-embed-divider`,t.id=`workspaceEmbedDivider`,e.appendChild(t),t.addEventListener(`mousedown`,t=>{t.preventDefault();let n=t.clientX,r=yh;e.classList.add(`resizing`);function i(t){let i=zh(r+(n-t.clientX));yh=i,e.style.setProperty(`--ws-embed-width`,`${i}px`)}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),Uh()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function Kh(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{if(vh){e.clientWidth<ph&&(bh=!1,vh=!1,xh=!1,Hh(),Uh(),F(r(`workspace.narrowViewportHint`),`error`));return}bh&&e.clientWidth>=ph&&Jh()}).observe(e)}async function qh(){if(vh)return!0;let e=document.getElementById(`workspacePanelContainer`);if(e&&e.style.display===`none`)return!1;let t=document.getElementById(`mainRow`);return(t?t.clientWidth:window.innerWidth)<ph?!1:(yh=zh(yh),document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await Xh(),Vh(),vh=!0,!0)}function Jh(){bh=!1,qh().then(e=>{e||(bh=!0)}).catch(e=>{i.warn(`[WorkspacePanel] deferred embed restore failed`,e),bh=!0})}async function Yh(){try{let e=await chrome.storage.local.get([hh,gh,_h]);if(typeof e[gh]==`number`&&e[gh]>=dh&&(yh=Math.round(e[gh])),!e[hh]||(xh=!0,e[_h]===!1)||(await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};requestAnimationFrame(()=>requestAnimationFrame(n)),setTimeout(n,500)}),await qh()))return;bh=!0}catch(e){i.warn(`[WorkspacePanel] restore embed state failed`,e)}}async function Xh(){let e=document.getElementById(`workspacePanel`);e.classList.contains(`expanded`)||(e.classList.add(`expanded`),Be(e),chrome.storage.local.set({[_h]:!0}).catch(()=>{}),await Sv(),J||await $h())}async function Zh(){let e=document.getElementById(`workspacePanel`);if(!(!e||e.classList.contains(`expanded`)))if(Dh=!1,xh){let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<ph){await Xh(),F(r(`workspace.narrowViewportHint`),`error`);return}await Xh(),yh=zh(yh),Vh(),vh=!0,bh=!1,await Uh()}else await Xh()}function Qh(){Hv()}async function $h(){let e=await Kt();if(!e){Ov(r(`workspace.noWorkspace`));return}ch=e,lh=[],eg(e)}async function eg(e){J=e,Y.clear(),Ev(),Dv(),by(),Og(),Gv&&Uv?(Wv=await wt(e,Uv),gg()):await og(e),Dg()}var tg=new Map,ng=3e4,rg=20;function ig(e){let t=tg.get(e);return t?Date.now()-t.timestamp>=ng?(tg.delete(e),null):(tg.delete(e),tg.set(e,t),t):null}function ag(e,t){tg.has(e)&&tg.delete(e),tg.set(e,t),tg.size>rg&&tg.delete(tg.keys().next().value)}async function og(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`;let n=ig(e);if(n){Mh=n.entries,gg();return}let i=await kt(e);if(!i.success){Ov(i.error||r(`workspace.loadDirFailed`));return}Mh=(i.entries||[]).map(t=>({...t,path:sg(`${e}/${t.name}`)})),ag(e,{entries:Mh,timestamp:Date.now()}),gg()}function sg(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function cg(e){tg.delete(e)}var lg=200,ug=32,dg=5,fg=null,pg=0;function mg(e){let t=Vt(e.name,e.type),n=e.type===`directory`?`—`:Lt(e.size),i=Gt(e.mtime),a=e.type===`file`&&It(e.name),o=Gv?e.fullPath:sg(`${J}/${e.name}`),s=Y.has(o),c=Gv&&e.matchPath!==J?sg(e.matchPath).replace(sg(ch),``).replace(/^\//,``)+`/`+e.name:``,l=Gv?Fh(e.name,Uv):Z(e.name);return`
|
|
1017
|
+
`,hn(`workspace`).appendChild(e),jh(),document.addEventListener(`session-switched`,()=>{sy().catch(e=>i.warn(`[WorkspacePanel] sync after session switch failed`,e))}),document.addEventListener(`session-workdir-changed`,e=>{let t=e.detail?.sessionId;t&&t!==C.activeSessionId||sy().catch(e=>i.warn(`[WorkspacePanel] sync after workdir change failed`,e))}),document.addEventListener(`session-hydrated`,()=>{sy().catch(e=>i.warn(`[WorkspacePanel] sync after session hydrated failed`,e))}),Jv(),Sv(),Gh(),Kh(),Yh(),i.debug(`[WorkspacePanel] workspace panelinitializing`)}function jh(){document.getElementById(`workspacePanelContainer`);let e=document.getElementById(`workspacePanel`);document.getElementById(`workspacePanelToggle`).addEventListener(`click`,async t=>{t.stopPropagation(),e.classList.contains(`expanded`)?Qh():await Zh()}),document.getElementById(`workspacePanelClose`).addEventListener(`click`,e=>{e.stopPropagation(),Qh()}),document.getElementById(`workspacePanelModeBtn`).addEventListener(`click`,async e=>{e.stopPropagation(),await Wh()});let t=document.getElementById(`workspaceSwitchBtn`);t&&t.addEventListener(`click`,async e=>{e.stopPropagation(),await iy()}),document.getElementById(`workspaceBackBtn`).addEventListener(`click`,e=>{e.stopPropagation(),wv()}),document.getElementById(`workspaceRefreshBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Tv()}),document.getElementById(`workspaceUploadBtn`).addEventListener(`click`,e=>{e.stopPropagation(),cv()}),document.getElementById(`workspaceNewFolderBtn`).addEventListener(`click`,e=>{e.stopPropagation(),my()}),document.getElementById(`workspaceAskBtn`).addEventListener(`click`,e=>{e.stopPropagation(),_y()}),document.getElementById(`workspaceDownloadDirBtn`).addEventListener(`click`,e=>{e.stopPropagation(),ov()}),document.getElementById(`workspaceBatchDeleteBtn`).addEventListener(`click`,e=>{e.stopPropagation(),ey()});let n=document.getElementById(`workspaceSearchInput`),i=document.getElementById(`workspaceToolbar`),a=i.querySelector(`.workspace-search-box`);function o(){return i.clientWidth<188}function s(){n.value.trim()?(a.classList.add(`search-box-expanded`),o()&&i.classList.add(`search-focused`)):(a.classList.remove(`search-box-expanded`),i.classList.remove(`search-focused`))}n.addEventListener(`input`,e=>{Xv(e),s()}),n.addEventListener(`focus`,()=>{o()&&i.classList.add(`search-focused`)}),n.addEventListener(`blur`,()=>{n.value.trim()||i.classList.remove(`search-focused`)}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`)e.stopPropagation(),Zv();else if(e.key===`Escape`)e.stopPropagation(),Qv();else if(e.key===`ArrowUp`){if(e.preventDefault(),Kv.length===0)return;qv===-1?qv=Kv.length-1:qv>0&&qv--,n.value=Kv[qv],Uv=n.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=Uv?``:`none`}else e.key===`ArrowDown`&&(e.preventDefault(),qv===-1||qv>=Kv.length-1?(qv=-1,n.value=``,Uv=``,document.getElementById(`workspaceSearchClear`).style.display=`none`):(qv++,n.value=Kv[qv],Uv=n.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=Uv?``:`none`))}),document.getElementById(`workspaceSearchBtn`).addEventListener(`click`,()=>{n.focus(),Zv()}),document.getElementById(`workspaceSearchClear`).addEventListener(`click`,Qv),document.getElementById(`workspacePanel`).querySelectorAll(`.workspace-file-header .sortable`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;Ch.field===t?Ch.asc=!Ch.asc:(Ch.field=t,Ch.asc=!0),Og(),gg()})}),document.getElementById(`workspaceSelectAll`).addEventListener(`click`,Eg),document.getElementById(`workspacePanelContent`).addEventListener(`click`,Cg),document.getElementById(`workspacePanelContent`).addEventListener(`dblclick`,wg),document.getElementById(`workspacePanelContent`).addEventListener(`keydown`,Sg),document.getElementById(`workspacePanelContent`).tabIndex=0,document.getElementById(`workspacePanelContent`).addEventListener(`dragstart`,xg);let c=null;document.getElementById(`workspacePanelContent`).addEventListener(`scroll`,()=>{fg&&(c&&cancelAnimationFrame(c),c=requestAnimationFrame(()=>{c=null,document.getElementById(`workspacePanelContent`).scrollTop!==pg&&hg()}))}),document.getElementById(`workspacePreviewClose`).addEventListener(`click`,()=>Q_()),document.getElementById(`workspacePreviewCopyBtn`).addEventListener(`click`,e=>z_(e)),document.getElementById(`workspacePreviewDownloadBtn`).addEventListener(`click`,H_),document.getElementById(`workspacePreviewOpenBrowserBtn`).addEventListener(`click`,U_),document.getElementById(`workspacePreviewFullscreenBtn`).addEventListener(`click`,q_),document.getElementById(`workspacePreviewMdToggleBtn`).addEventListener(`click`,J_),document.getElementById(`workspacePreviewEditBtn`).addEventListener(`click`,$_),document.getElementById(`workspacePreviewSaveBtn`).addEventListener(`click`,ev),document.getElementById(`workspacePreviewCancelBtn`).addEventListener(`click`,tv),O_(),document.addEventListener(`keydown`,iv),document.getElementById(`workspacePreviewFilename`).addEventListener(`click`,async e=>{let t=document.getElementById(`workspacePreviewArea`),n=t.dataset.previewName,i=t.dataset.previewPath;if(n){if((e.ctrlKey||e.metaKey)&&!e.shiftKey){e.preventDefault();try{await navigator.clipboard.writeText(n),P(r(`workspace.copiedFileName`,{name:n}))}catch{P(r(`workspace.copyFailed`),`error`)}}else if((e.ctrlKey||e.metaKey)&&e.shiftKey){if(e.preventDefault(),!i)return;try{await navigator.clipboard.writeText(i),P(r(`workspace.copiedPath`,{path:i}))}catch{P(r(`workspace.copyFailed`),`error`)}}}}),xv(),chrome.storage.local.onChanged.addListener(Cv);let l=document.createElement(`input`);l.type=`file`,l.multiple=!0,l.id=`workspaceFileInput`,l.style.display=`none`,l.addEventListener(`change`,lv),document.body.appendChild(l)}var Mh=[];function Nh(e){lh.push(e),lh.length>uh&&lh.shift()}function Ph(e){if(!e||typeof e!=`string`)return`unnamed`;let t=e.replace(/[<>:"|?*\\/\x00-\x1f]/g,`_`);return t=t.replace(/\.+$/,``),t=t.trim(),t||=`unnamed`,t}function Fh(e,t){let n=Z(e);if(!t)return n;let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return n.replace(RegExp(`(${r})`,`gi`),`<mark class="search-highlight">$1</mark>`)}var Ih=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/></svg>`,Lh=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/><path d="m8 9-3 3 3 3"/></svg>`;function Rh(){let e=document.getElementById(`mainRow`),t=e?e.clientWidth:window.innerWidth;return Math.max(dh,t-fh)}function zh(e){return Math.max(dh,Math.min(e,Rh()))}function Bh(e){let t=document.getElementById(`workspacePanelModeBtn`);t&&(t.title=r(e?`workspace.floatMode`:`workspace.embedMode`),t.innerHTML=e?Lh:Ih)}function Vh(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;let t=document.getElementById(`mainRow`);t&&e.parentElement!==t&&t.appendChild(e),e.classList.add(`embedded`),e.style.setProperty(`--ws-embed-width`,`${yh}px`),Bh(!0)}function Hh(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;e.classList.remove(`embedded`);let t=hn(`workspace`);t&&e.parentElement!==t&&t.appendChild(e),Bh(!1)}async function Uh(){try{await chrome.storage.local.set({[hh]:vh,[gh]:yh})}catch(e){i.warn(`[WorkspacePanel] persist embed state failed`,e)}}async function Wh(){if(vh){vh=!1,xh=!1,bh=!1,Hh(),await Uh();return}let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<ph){P(r(`workspace.narrowViewportHint`),`error`);return}document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await Xh(),yh=zh(yh),Vh(),vh=!0,xh=!0,bh=!1,await Uh()}function Gh(){let e=document.getElementById(`workspacePanelContainer`),t=document.createElement(`div`);t.className=`workspace-embed-divider`,t.id=`workspaceEmbedDivider`,e.appendChild(t),t.addEventListener(`mousedown`,t=>{t.preventDefault();let n=t.clientX,r=yh;e.classList.add(`resizing`);function i(t){let i=zh(r+(n-t.clientX));yh=i,e.style.setProperty(`--ws-embed-width`,`${i}px`)}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),Uh()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function Kh(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{if(vh){e.clientWidth<ph&&(bh=!1,vh=!1,xh=!1,Hh(),Uh(),P(r(`workspace.narrowViewportHint`),`error`));return}bh&&e.clientWidth>=ph&&Jh()}).observe(e)}async function qh(){if(vh)return!0;let e=document.getElementById(`workspacePanelContainer`);if(e&&e.style.display===`none`)return!1;let t=document.getElementById(`mainRow`);return(t?t.clientWidth:window.innerWidth)<ph?!1:(yh=zh(yh),document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await Xh(),Vh(),vh=!0,!0)}function Jh(){bh=!1,qh().then(e=>{e||(bh=!0)}).catch(e=>{i.warn(`[WorkspacePanel] deferred embed restore failed`,e),bh=!0})}async function Yh(){try{let e=await chrome.storage.local.get([hh,gh,_h]);if(typeof e[gh]==`number`&&e[gh]>=dh&&(yh=Math.round(e[gh])),!e[hh]||(xh=!0,e[_h]===!1)||(await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};requestAnimationFrame(()=>requestAnimationFrame(n)),setTimeout(n,500)}),await qh()))return;bh=!0}catch(e){i.warn(`[WorkspacePanel] restore embed state failed`,e)}}async function Xh(){let e=document.getElementById(`workspacePanel`);e.classList.contains(`expanded`)||(e.classList.add(`expanded`),Fe(e),chrome.storage.local.set({[_h]:!0}).catch(()=>{}),await Sv(),J||await $h())}async function Zh(){let e=document.getElementById(`workspacePanel`);if(!(!e||e.classList.contains(`expanded`)))if(Dh=!1,xh){let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<ph){await Xh(),P(r(`workspace.narrowViewportHint`),`error`);return}await Xh(),yh=zh(yh),Vh(),vh=!0,bh=!1,await Uh()}else await Xh()}function Qh(){Hv()}async function $h(){let e=await Kt();if(!e){Ov(r(`workspace.noWorkspace`));return}ch=e,lh=[],eg(e)}async function eg(e){J=e,Y.clear(),Ev(),Dv(),by(),Og(),Gv&&Uv?(Wv=await wt(e,Uv),gg()):await og(e),Dg()}var tg=new Map,ng=3e4,rg=20;function ig(e){let t=tg.get(e);return t?Date.now()-t.timestamp>=ng?(tg.delete(e),null):(tg.delete(e),tg.set(e,t),t):null}function ag(e,t){tg.has(e)&&tg.delete(e),tg.set(e,t),tg.size>rg&&tg.delete(tg.keys().next().value)}async function og(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`;let n=ig(e);if(n){Mh=n.entries,gg();return}let i=await kt(e);if(!i.success){Ov(i.error||r(`workspace.loadDirFailed`));return}Mh=(i.entries||[]).map(t=>({...t,path:sg(`${e}/${t.name}`)})),ag(e,{entries:Mh,timestamp:Date.now()}),gg()}function sg(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function cg(e){tg.delete(e)}var lg=200,ug=32,dg=5,fg=null,pg=0;function mg(e){let t=Vt(e.name,e.type),n=e.type===`directory`?`—`:Lt(e.size),i=Gt(e.mtime),a=e.type===`file`&&It(e.name),o=Gv?e.fullPath:sg(`${J}/${e.name}`),s=Y.has(o),c=Gv&&e.matchPath!==J?sg(e.matchPath).replace(sg(ch),``).replace(/^\//,``)+`/`+e.name:``,l=Gv?Fh(e.name,Uv):Z(e.name);return`
|
|
1018
1018
|
<div class="workspace-file-item ${e.type} ${s?`selected`:``}" data-path="${Z(o)}" data-type="${e.type}" data-name="${Z(e.name)}" draggable="true">
|
|
1019
1019
|
<span class="workspace-file-select" data-action="select">
|
|
1020
1020
|
<span class="workspace-checkbox ${s?`checked`:``}"></span>
|
|
@@ -1031,7 +1031,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1031
1031
|
<button class="workspace-file-btn ask" title="${r(`workspace.askFile`)}" data-action="ask"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="13" height="13"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg></button>
|
|
1032
1032
|
<button class="workspace-file-btn delete" title="${r(`workspace.delete`)}" data-action="delete"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="13" height="13"><path d="M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg></button>
|
|
1033
1033
|
</span>
|
|
1034
|
-
</div>`}function hg(){if(!fg)return;let{sorted:e}=fg,t=document.getElementById(`workspacePanelContent`),n=t.clientHeight,r=t.scrollTop,i=fg.itemHeight,a=Math.max(0,Math.floor(r/i)-dg),o=Math.min(e.length,Math.ceil((r+n)/i)+dg),s=`<div class="workspace-file-list" style="padding-top:${a*i}px;padding-bottom:${(e.length-o)*i}px;">`;for(let t=a;t<o;t++)s+=mg(e[t]);s+=`</div>`,t.innerHTML=s;let c=t.querySelector(`.workspace-file-item`);if(c){let a=c.offsetHeight;if(a&&Math.abs(a-i)>2){fg.itemHeight=a;let i=Math.max(0,Math.floor(r/a)-dg),o=Math.min(e.length,Math.ceil((r+n)/a)+dg),s=`<div class="workspace-file-list" style="padding-top:${i*a}px;padding-bottom:${(e.length-o)*a}px;">`;for(let t=i;t<o;t++)s+=mg(e[t]);s+=`</div>`,t.innerHTML=s}}vg(),hv(),pg=t.scrollTop}function gg(){let e=document.getElementById(`workspacePanelContent`),t=[];if(t=Gv?Wv:[...Mh],t.length===0){fg=null,e.innerHTML=Gv?`<div class="workspace-panel-empty">${r(`workspace.noMatch`)}</div>`:`<div class="workspace-panel-empty">${r(`workspace.dirEmpty`)}</div>`;return}let n=t.filter(e=>e.type===`directory`),i=t.filter(e=>e.type!==`directory`),a=(e,t)=>{let n;if(Ch.field===`name`)n=e.name.localeCompare(t.name);else if(Ch.field===`size`){if(e.type===`directory`&&t.type!==`directory`)return Ch.asc?-1:1;if(e.type!==`directory`&&t.type===`directory`)return Ch.asc?1:-1;n=(e.size||0)-(t.size||0)}else n=(e.mtime||0)-(t.mtime||0);return Ch.asc?n:-n},o=n.sort(a),s=i.sort(a),c;if(c=Ch.field===`name`?Ch.asc?[...o,...s]:[...s.reverse(),...o.reverse()]:[...o,...s],Eh=-1,c.length>lg){fg={sorted:c,itemHeight:ug},e.scrollTop=0,hg();return}fg=null;let l=`<div class="workspace-file-list">`;for(let e of c)l+=mg(e);l+=`</div>`,e.innerHTML=l}function _g(){let e=document.getElementById(`workspacePanelContent`);return e?Array.from(e.querySelectorAll(`.workspace-file-item`)):[]}function vg(){let e=document.getElementById(`workspacePanelContent`);if(fg&&Eh>=0){let{sorted:t,itemHeight:n}=fg;if(Eh>=t.length)return;let r=e.scrollTop,i=e.clientHeight,a=Eh*n,o=a+n;if(a<r||o>r+i){e.scrollTop=Math.max(0,a-(i-n)/2),hg();return}}let t=_g();if(t.forEach(e=>e.classList.remove(`keyboard-focused`)),!(Eh<0))if(fg){let e=fg.sorted[Eh];if(!e)return;let n=Gv?e.fullPath:sg(`${J}/${e.name}`),r=t.find(e=>e.dataset.path===n);r&&r.classList.add(`keyboard-focused`)}else Eh<t.length&&(t[Eh].classList.add(`keyboard-focused`),t[Eh].scrollIntoView({block:`nearest`,behavior:`smooth`}))}function yg(e){let t=_g();t.length!==0&&(Eh=Eh===-1?e>0?0:t.length-1:Math.max(0,Math.min(t.length-1,Eh+e)),vg())}function bg(){let e=_g();if(Eh<0||Eh>=e.length)return null;let t=e[Eh];return{el:t,path:t.dataset.path,name:t.dataset.name,type:t.dataset.type}}function xg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;let n=t.dataset.path,r=t.dataset.type;n&&(e.dataTransfer.effectAllowed=`copy`,e.dataTransfer.setData(`application/x-workspace-file`,JSON.stringify({path:n,name:t.dataset.name,type:r})))}async function Sg(e){let t=e.target.tagName;if(!(t===`INPUT`||t===`TEXTAREA`))switch(e.key){case`ArrowDown`:e.preventDefault(),yg(1);break;case`ArrowUp`:e.preventDefault(),yg(-1);break;case`Enter`:{e.preventDefault();let t=bg();if(!t)return;t.type===`directory`?(Nh(J),await eg(t.path)):await Bg(t.path,t.name);break}case`Delete`:{e.preventDefault();let t=bg();if(!t)return;await $v(t.path,t.name,t.type);break}case`F2`:{e.preventDefault();let t=bg();if(!t)return;await py(t.path,t.name,t.type);break}case` `:{e.preventDefault();let t=bg();if(!t)return;Tg(t.path),yg(1);break}case`Escape`:Eh=-1,vg();break}}async function Cg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;Dh=!1;let n=t.dataset.path,i=t.dataset.type,a=e.target.closest(`[data-action]`),o=_g(),s;if(fg){let e=t.dataset.path;s=fg.sorted.findIndex(t=>(Gv?t.fullPath:sg(`${J}/${t.name}`))===e)}else s=o.indexOf(t);if(s>=0&&(Eh=s,vg()),e.target.closest(`.workspace-file-select`)){e.stopPropagation(),Tg(n);return}if(a){let r=a.dataset.action;e.stopPropagation(),r===`preview`?await Bg(n,t.dataset.name):r===`info`?await ny(n,t.dataset.name,i):r===`download`?await av(n,t.dataset.name):r===`ask`?await gy([n]):r===`delete`?await $v(n,t.dataset.name,i):r===`rename`&&await py(n,t.dataset.name,i);return}if((e.ctrlKey||e.metaKey)&&!e.shiftKey){e.stopPropagation(),navigator.clipboard.writeText(t.dataset.name).then(()=>{F(r(`workspace.copiedFileName`,{name:t.dataset.name}))}).catch(()=>{F(r(`workspace.copyFailed`),`error`)});return}if((e.ctrlKey||e.metaKey)&&e.shiftKey){e.stopPropagation(),navigator.clipboard.writeText(n).then(()=>{F(r(`workspace.copiedPath`,{path:n}))}).catch(()=>{F(r(`workspace.copyFailed`),`error`)});return}if(i===`directory`){e.stopPropagation(),Nh(J),await eg(n);return}}async function wg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;Dh=!1;let n=t.dataset.path,r=t.dataset.type,i=t.dataset.name;if(!e.target.closest(`[data-action]`)&&!e.target.closest(`.workspace-file-select`)){if(r===`directory`){e.stopPropagation(),Nh(J),await eg(n);return}r===`file`&&It(i)&&(e.stopPropagation(),await Bg(n,i))}}function Tg(e){Y.has(e)?Y.delete(e):Y.add(e),by(),Dg();let t=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.path===e);if(t){let n=Y.has(e);t.classList.toggle(`selected`,n);let r=t.querySelector(`.workspace-checkbox`);r&&r.classList.toggle(`checked`,n)}}function Eg(){let e=(Gv?Wv:Mh).map(e=>Gv?e.fullPath:sg(`${J}/${e.name}`));if(e.length>0&&e.every(e=>Y.has(e)))for(let t of e)Y.delete(t);else for(let t of e)Y.add(t);by(),Dg();for(let e of document.querySelectorAll(`.workspace-file-item`)){let t=Y.has(e.dataset.path);e.classList.toggle(`selected`,t);let n=e.querySelector(`.workspace-checkbox`);n&&n.classList.toggle(`checked`,t)}}function Dg(){let e=(Gv?Wv:Mh).map(e=>Gv?e.fullPath:sg(`${J}/${e.name}`)),t=document.getElementById(`workspaceSelectAll`);if(!t)return;let n=t.querySelector(`.workspace-checkbox`);e.length===0?(n.classList.remove(`checked`),n.classList.remove(`indeterminate`)):e.every(e=>Y.has(e))?(n.classList.add(`checked`),n.classList.remove(`indeterminate`)):e.some(e=>Y.has(e))?(n.classList.remove(`checked`),n.classList.add(`indeterminate`)):(n.classList.remove(`checked`),n.classList.remove(`indeterminate`))}function Og(){[`name`,`size`,`time`].forEach(e=>{let t=document.getElementById(`sort${e.charAt(0).toUpperCase()+e.slice(1)}Indicator`);t&&(Ch.field===e?t.textContent=Ch.asc?`▲`:`▼`:t.textContent=``)})}var kg=1024*1024,Ag=50*1024*1024,jg=20*1024*1024,Mg=50*1024*1024,Ng=50*1024*1024,Pg=50*1024*1024,Fg=200*1024*1024,Ig=100*1024*1024,Lg=1e4,Rg=2e3;async function zg(e){let t=await jt();if(!t)throw Error(r(`workspace.agentNotPaired`));let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(t)},body:JSON.stringify({path:e})});if(!n.ok){let e=await n.text().catch(()=>n.statusText);throw Error(typeof e==`string`?e:`HTTP ${n.status}`)}let i=n.body.getReader(),a=[];for(;;){let{done:e,value:t}=await i.read();if(e)break;a.push(t)}let o=a.reduce((e,t)=>e+t.length,0),s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.length;return s.buffer}async function Bg(e,t){Oh&&Oh.abort(),Oh=new AbortController;let n=Oh.signal,a=document.getElementById(`workspacePreviewArea`),o=document.getElementById(`workspacePreviewContent`),s=document.getElementById(`workspacePreviewFilename`),c=document.getElementById(`workspacePreviewLineCount`),l=document.getElementById(`workspacePreviewCopyBtn`),u=document.getElementById(`workspacePreviewDownloadBtn`),d=document.getElementById(`workspacePreviewOpenBrowserBtn`),f=document.getElementById(`workspacePreviewFullscreenBtn`),p=document.getElementById(`workspacePreviewMdToggleBtn`);s.textContent=t,c.textContent=``,o.classList.remove(`xlsx-mode`),o.classList.remove(`markdown-rendered`),o.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`,a.style.display=`flex`,l.style.display=``,u.style.display=``,d.style.display=`none`,f.style.display=`none`,p.style.display=`none`,p.classList.remove(`active`),W_(p,!1);let m=document.getElementById(`workspacePreviewEditBtn`),h=document.getElementById(`workspacePreviewSaveBtn`),g=document.getElementById(`workspacePreviewCancelBtn`);m.style.display=`none`,h.style.display=`none`,g.style.display=`none`,delete a.dataset.editMode,delete a.dataset.origContent,a.classList.remove(`has-unsaved`),s.classList.remove(`modified`),a.classList.remove(`fullscreen`),document.getElementById(`workspacePanel`).classList.remove(`preview-fullscreen`),a.dataset.previewPath=e,a.dataset.previewName=t,delete a.dataset.previewType,delete a.dataset.previewSheets,delete a.dataset.previewMode,delete a.dataset.htmlText;let _=Dt(t),v=Mh.find(t=>t.path===e)||Wv.find(t=>t.fullPath===e),y=v?v.size:0;if(_===`text`){if(l.style.display=``,y>kg){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.fileTooLargeNoPreview`,{size:Lt(y)})}</div>`;return}let n=(t.split(`.`).pop()||``).toLowerCase(),i=await qt(e);if(!i.success){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.previewFailed`,{error:Z(i.error||r(`workspace.unknownError`))})}</div>`;return}let s=i.size||0;if(s>kg){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.fileTooLargeNoPreview`,{size:Lt(s)})}</div>`;return}let h=i.content||``;if(!Yt(t)&&Jt(h)){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.binaryFileNoPreview`)}</div>`;return}if(m.style.display=``,f.style.display=``,a.dataset.origContent=h,n===`md`||n===`markdown`){p.style.display=``,a.dataset.markdownText=h,a.dataset.previewMode=`markdown`,o.classList.add(`markdown-rendered`),p.classList.add(`active`),p.title=r(`workspace.switchToSourcePreview`),W_(p,!0),l.style.display=``;let e=document.getElementById(`workspacePreviewDownloadBtn`);e&&(e.style.display=`none`);let t=document.getElementById(`workspacePreviewExportMenu`);t&&(t.style.display=``),o.innerHTML=`<div class="markdown-body workspace-preview-markdown">${et(h)}</div>`,X_(o),Z_(o),Ze(),c.textContent=``,Y_(!0);return}if(n===`html`||n===`htm`){p.style.display=``,a.dataset.htmlText=h,a.dataset.previewMode=`html`,o.classList.add(`markdown-rendered`),p.classList.add(`active`),p.title=r(`workspace.switchToSourcePreview`),W_(p,!0),l.style.display=``,u.style.display=`none`,d.style.display=``,c.textContent=``,K_(o,h),Y_(!0);return}let g=kv(t),_=h.split(`
|
|
1034
|
+
</div>`}function hg(){if(!fg)return;let{sorted:e}=fg,t=document.getElementById(`workspacePanelContent`),n=t.clientHeight,r=t.scrollTop,i=fg.itemHeight,a=Math.max(0,Math.floor(r/i)-dg),o=Math.min(e.length,Math.ceil((r+n)/i)+dg),s=`<div class="workspace-file-list" style="padding-top:${a*i}px;padding-bottom:${(e.length-o)*i}px;">`;for(let t=a;t<o;t++)s+=mg(e[t]);s+=`</div>`,t.innerHTML=s;let c=t.querySelector(`.workspace-file-item`);if(c){let a=c.offsetHeight;if(a&&Math.abs(a-i)>2){fg.itemHeight=a;let i=Math.max(0,Math.floor(r/a)-dg),o=Math.min(e.length,Math.ceil((r+n)/a)+dg),s=`<div class="workspace-file-list" style="padding-top:${i*a}px;padding-bottom:${(e.length-o)*a}px;">`;for(let t=i;t<o;t++)s+=mg(e[t]);s+=`</div>`,t.innerHTML=s}}vg(),hv(),pg=t.scrollTop}function gg(){let e=document.getElementById(`workspacePanelContent`),t=[];if(t=Gv?Wv:[...Mh],t.length===0){fg=null,e.innerHTML=Gv?`<div class="workspace-panel-empty">${r(`workspace.noMatch`)}</div>`:`<div class="workspace-panel-empty">${r(`workspace.dirEmpty`)}</div>`;return}let n=t.filter(e=>e.type===`directory`),i=t.filter(e=>e.type!==`directory`),a=(e,t)=>{let n;if(Ch.field===`name`)n=e.name.localeCompare(t.name);else if(Ch.field===`size`){if(e.type===`directory`&&t.type!==`directory`)return Ch.asc?-1:1;if(e.type!==`directory`&&t.type===`directory`)return Ch.asc?1:-1;n=(e.size||0)-(t.size||0)}else n=(e.mtime||0)-(t.mtime||0);return Ch.asc?n:-n},o=n.sort(a),s=i.sort(a),c;if(c=Ch.field===`name`?Ch.asc?[...o,...s]:[...s.reverse(),...o.reverse()]:[...o,...s],Eh=-1,c.length>lg){fg={sorted:c,itemHeight:ug},e.scrollTop=0,hg();return}fg=null;let l=`<div class="workspace-file-list">`;for(let e of c)l+=mg(e);l+=`</div>`,e.innerHTML=l}function _g(){let e=document.getElementById(`workspacePanelContent`);return e?Array.from(e.querySelectorAll(`.workspace-file-item`)):[]}function vg(){let e=document.getElementById(`workspacePanelContent`);if(fg&&Eh>=0){let{sorted:t,itemHeight:n}=fg;if(Eh>=t.length)return;let r=e.scrollTop,i=e.clientHeight,a=Eh*n,o=a+n;if(a<r||o>r+i){e.scrollTop=Math.max(0,a-(i-n)/2),hg();return}}let t=_g();if(t.forEach(e=>e.classList.remove(`keyboard-focused`)),!(Eh<0))if(fg){let e=fg.sorted[Eh];if(!e)return;let n=Gv?e.fullPath:sg(`${J}/${e.name}`),r=t.find(e=>e.dataset.path===n);r&&r.classList.add(`keyboard-focused`)}else Eh<t.length&&(t[Eh].classList.add(`keyboard-focused`),t[Eh].scrollIntoView({block:`nearest`,behavior:`smooth`}))}function yg(e){let t=_g();t.length!==0&&(Eh=Eh===-1?e>0?0:t.length-1:Math.max(0,Math.min(t.length-1,Eh+e)),vg())}function bg(){let e=_g();if(Eh<0||Eh>=e.length)return null;let t=e[Eh];return{el:t,path:t.dataset.path,name:t.dataset.name,type:t.dataset.type}}function xg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;let n=t.dataset.path,r=t.dataset.type;n&&(e.dataTransfer.effectAllowed=`copy`,e.dataTransfer.setData(`application/x-workspace-file`,JSON.stringify({path:n,name:t.dataset.name,type:r})))}async function Sg(e){let t=e.target.tagName;if(!(t===`INPUT`||t===`TEXTAREA`))switch(e.key){case`ArrowDown`:e.preventDefault(),yg(1);break;case`ArrowUp`:e.preventDefault(),yg(-1);break;case`Enter`:{e.preventDefault();let t=bg();if(!t)return;t.type===`directory`?(Nh(J),await eg(t.path)):await Bg(t.path,t.name);break}case`Delete`:{e.preventDefault();let t=bg();if(!t)return;await $v(t.path,t.name,t.type);break}case`F2`:{e.preventDefault();let t=bg();if(!t)return;await py(t.path,t.name,t.type);break}case` `:{e.preventDefault();let t=bg();if(!t)return;Tg(t.path),yg(1);break}case`Escape`:Eh=-1,vg();break}}async function Cg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;Dh=!1;let n=t.dataset.path,i=t.dataset.type,a=e.target.closest(`[data-action]`),o=_g(),s;if(fg){let e=t.dataset.path;s=fg.sorted.findIndex(t=>(Gv?t.fullPath:sg(`${J}/${t.name}`))===e)}else s=o.indexOf(t);if(s>=0&&(Eh=s,vg()),e.target.closest(`.workspace-file-select`)){e.stopPropagation(),Tg(n);return}if(a){let r=a.dataset.action;e.stopPropagation(),r===`preview`?await Bg(n,t.dataset.name):r===`info`?await ny(n,t.dataset.name,i):r===`download`?await av(n,t.dataset.name):r===`ask`?await gy([n]):r===`delete`?await $v(n,t.dataset.name,i):r===`rename`&&await py(n,t.dataset.name,i);return}if((e.ctrlKey||e.metaKey)&&!e.shiftKey){e.stopPropagation(),navigator.clipboard.writeText(t.dataset.name).then(()=>{P(r(`workspace.copiedFileName`,{name:t.dataset.name}))}).catch(()=>{P(r(`workspace.copyFailed`),`error`)});return}if((e.ctrlKey||e.metaKey)&&e.shiftKey){e.stopPropagation(),navigator.clipboard.writeText(n).then(()=>{P(r(`workspace.copiedPath`,{path:n}))}).catch(()=>{P(r(`workspace.copyFailed`),`error`)});return}if(i===`directory`){e.stopPropagation(),Nh(J),await eg(n);return}}async function wg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;Dh=!1;let n=t.dataset.path,r=t.dataset.type,i=t.dataset.name;if(!e.target.closest(`[data-action]`)&&!e.target.closest(`.workspace-file-select`)){if(r===`directory`){e.stopPropagation(),Nh(J),await eg(n);return}r===`file`&&It(i)&&(e.stopPropagation(),await Bg(n,i))}}function Tg(e){Y.has(e)?Y.delete(e):Y.add(e),by(),Dg();let t=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.path===e);if(t){let n=Y.has(e);t.classList.toggle(`selected`,n);let r=t.querySelector(`.workspace-checkbox`);r&&r.classList.toggle(`checked`,n)}}function Eg(){let e=(Gv?Wv:Mh).map(e=>Gv?e.fullPath:sg(`${J}/${e.name}`));if(e.length>0&&e.every(e=>Y.has(e)))for(let t of e)Y.delete(t);else for(let t of e)Y.add(t);by(),Dg();for(let e of document.querySelectorAll(`.workspace-file-item`)){let t=Y.has(e.dataset.path);e.classList.toggle(`selected`,t);let n=e.querySelector(`.workspace-checkbox`);n&&n.classList.toggle(`checked`,t)}}function Dg(){let e=(Gv?Wv:Mh).map(e=>Gv?e.fullPath:sg(`${J}/${e.name}`)),t=document.getElementById(`workspaceSelectAll`);if(!t)return;let n=t.querySelector(`.workspace-checkbox`);e.length===0?(n.classList.remove(`checked`),n.classList.remove(`indeterminate`)):e.every(e=>Y.has(e))?(n.classList.add(`checked`),n.classList.remove(`indeterminate`)):e.some(e=>Y.has(e))?(n.classList.remove(`checked`),n.classList.add(`indeterminate`)):(n.classList.remove(`checked`),n.classList.remove(`indeterminate`))}function Og(){[`name`,`size`,`time`].forEach(e=>{let t=document.getElementById(`sort${e.charAt(0).toUpperCase()+e.slice(1)}Indicator`);t&&(Ch.field===e?t.textContent=Ch.asc?`▲`:`▼`:t.textContent=``)})}var kg=1024*1024,Ag=50*1024*1024,jg=20*1024*1024,Mg=50*1024*1024,Ng=50*1024*1024,Pg=50*1024*1024,Fg=200*1024*1024,Ig=100*1024*1024,Lg=1e4,Rg=2e3;async function zg(e){let t=await jt();if(!t)throw Error(r(`workspace.agentNotPaired`));let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(t)},body:JSON.stringify({path:e})});if(!n.ok){let e=await n.text().catch(()=>n.statusText);throw Error(typeof e==`string`?e:`HTTP ${n.status}`)}let i=n.body.getReader(),a=[];for(;;){let{done:e,value:t}=await i.read();if(e)break;a.push(t)}let o=a.reduce((e,t)=>e+t.length,0),s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.length;return s.buffer}async function Bg(e,t){Oh&&Oh.abort(),Oh=new AbortController;let n=Oh.signal,a=document.getElementById(`workspacePreviewArea`),o=document.getElementById(`workspacePreviewContent`),s=document.getElementById(`workspacePreviewFilename`),c=document.getElementById(`workspacePreviewLineCount`),l=document.getElementById(`workspacePreviewCopyBtn`),u=document.getElementById(`workspacePreviewDownloadBtn`),d=document.getElementById(`workspacePreviewOpenBrowserBtn`),f=document.getElementById(`workspacePreviewFullscreenBtn`),p=document.getElementById(`workspacePreviewMdToggleBtn`);s.textContent=t,c.textContent=``,o.classList.remove(`xlsx-mode`),o.classList.remove(`markdown-rendered`),o.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`,a.style.display=`flex`,l.style.display=``,u.style.display=``,d.style.display=`none`,f.style.display=`none`,p.style.display=`none`,p.classList.remove(`active`),W_(p,!1);let m=document.getElementById(`workspacePreviewEditBtn`),h=document.getElementById(`workspacePreviewSaveBtn`),g=document.getElementById(`workspacePreviewCancelBtn`);m.style.display=`none`,h.style.display=`none`,g.style.display=`none`,delete a.dataset.editMode,delete a.dataset.origContent,a.classList.remove(`has-unsaved`),s.classList.remove(`modified`),a.classList.remove(`fullscreen`),document.getElementById(`workspacePanel`).classList.remove(`preview-fullscreen`),a.dataset.previewPath=e,a.dataset.previewName=t,delete a.dataset.previewType,delete a.dataset.previewSheets,delete a.dataset.previewMode,delete a.dataset.htmlText;let _=Dt(t),v=Mh.find(t=>t.path===e)||Wv.find(t=>t.fullPath===e),y=v?v.size:0;if(_===`text`){if(l.style.display=``,y>kg){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.fileTooLargeNoPreview`,{size:Lt(y)})}</div>`;return}let n=(t.split(`.`).pop()||``).toLowerCase(),i=await qt(e);if(!i.success){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.previewFailed`,{error:Z(i.error||r(`workspace.unknownError`))})}</div>`;return}let s=i.size||0;if(s>kg){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.fileTooLargeNoPreview`,{size:Lt(s)})}</div>`;return}let h=i.content||``;if(!Yt(t)&&Jt(h)){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.binaryFileNoPreview`)}</div>`;return}if(m.style.display=``,f.style.display=``,a.dataset.origContent=h,n===`md`||n===`markdown`){p.style.display=``,a.dataset.markdownText=h,a.dataset.previewMode=`markdown`,o.classList.add(`markdown-rendered`),p.classList.add(`active`),p.title=r(`workspace.switchToSourcePreview`),W_(p,!0),l.style.display=``;let e=document.getElementById(`workspacePreviewDownloadBtn`);e&&(e.style.display=`none`);let t=document.getElementById(`workspacePreviewExportMenu`);t&&(t.style.display=``),o.innerHTML=`<div class="markdown-body workspace-preview-markdown">${et(h)}</div>`,X_(o),Z_(o),Ze(),c.textContent=``,Y_(!0);return}if(n===`html`||n===`htm`){p.style.display=``,a.dataset.htmlText=h,a.dataset.previewMode=`html`,o.classList.add(`markdown-rendered`),p.classList.add(`active`),p.title=r(`workspace.switchToSourcePreview`),W_(p,!0),l.style.display=``,u.style.display=`none`,d.style.display=``,c.textContent=``,K_(o,h),Y_(!0);return}let g=kv(t),_=h.split(`
|
|
1035
1035
|
`);c.textContent=r(`workspace.lineCount`,{count:_.length});let v=_.length>Lg,b=v?_.slice(0,Lg):_,x=`<table class="workspace-preview-code-table"><tbody>`;for(let e=0;e<b.length;e++)x+=`<tr><td class="line-num">${e+1}</td><td class="line-content"><code class="${g}">${Z(b[e])}</code></td></tr>`;v&&(x+=`<tr><td class="line-num">…</td><td class="line-content"><code>${r(`workspace.truncatedHint`,{shown:Lg,total:_.length})}</code></td></tr>`),x+=`</tbody></table>`,o.innerHTML=x;return}l.style.display=`none`,d.style.display=_===`pdf`||_===`image`?``:`none`;try{if(y>({pdf:Ag,docx:jg,pptx:Mg,xlsx:Ng,image:Pg,video:Fg,audio:Ig}[_]||kg)){o.innerHTML=`<div class="workspace-panel-error">${r(_===`pdf`||_===`image`?`workspace.fileTooLargeOpenInBrowser`:`workspace.fileTooLargeNoPreview`,{size:Lt(y)})}</div>`;return}if(_===`xlsx`){f.style.display=``,await y_(t,o,a);return}let i=await zg(e);switch(_){case`pdf`:f.style.display=``,await t_(i,t,o,a,n);break;case`docx`:f.style.display=``,await n_(i,o);break;case`pptx`:f.style.display=``,await p_(i,t,o,a,n);break;case`image`:f.style.display=``,await S_(i,t,o,n);break;case`video`:case`audio`:f.style.display=``,await w_(i,t,_,o,a);break;default:o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.unsupportedFileType`)}</div>`}}catch(t){i.error(`[WorkspacePanel] preview failed:`,e,t),o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.previewFailed`,{error:Z((t instanceof Error?t.message:typeof t==`string`?t:String(t))||r(`workspace.unknownError`))})}</div>`}}var Vg=null,Hg=1,Ug=1,Wg=1,Gg=1,Kg=0,qg=0,Jg=!1,Yg=0,Xg=0,Zg=0,Qg=0,$g=null,e_=1;async function t_(t,n,i,a,o){let s=await A(()=>import(`./pdf-DnVqBaAN.js`).then(t=>e(t.default,1)),__vite__mapDeps([4,1,5]));s.GlobalWorkerOptions.workerSrc=`libs/pdf.worker.min.js`;let c=await s.getDocument({data:t}).promise;Vg=c,Hg=1,Ug=1,Wg=1,Gg=1,e_=1,Kg=0,qg=0,a.dataset.previewType=`pdf`;let l=c.numPages;document.getElementById(`workspacePreviewLineCount`).textContent=r(`workspace.pageCount`,{count:l}),i.innerHTML=`
|
|
1036
1036
|
<div class="pdf-wrap">
|
|
1037
1037
|
<div class="pdf-toolbar">
|
|
@@ -1061,7 +1061,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1061
1061
|
</div>
|
|
1062
1062
|
</div>
|
|
1063
1063
|
</div>
|
|
1064
|
-
`;let u=document.getElementById(`pdfViewport`),d=document.getElementById(`pdfPan`),f=document.getElementById(`pdfCanvas`),p=document.getElementById(`pdfZoomInfo`);function m(){d.style.transform=`translate(${Kg}px, ${qg}px) scale(${Wg})`,p.textContent=Math.round(Ug*100)+`%`,Jg||(u.style.cursor=Ug>Gg?`grab`:`default`)}function h(){Ug<=Gg&&(Kg=0,qg=0)}function g(e,t,n){let r=Ug;if(Ug=Math.max(.05,Math.min(5,e)),Wg=Ug/e_,t!==void 0&&n!==void 0){let e=u.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=Ug/r;Kg=i-o*(i-Kg),qg=a-o*(a-qg)}h(),m(),_()}function _(){$g&&clearTimeout($g),$g=setTimeout(()=>{v()},180)}async function v(){if(!Vg)return;let e=await Vg.getPage(Hg),t=window.devicePixelRatio||1,n=Math.max(Ug,1);e_=n;let r=e.getViewport({scale:n});f.width=Math.floor(r.width*t),f.height=Math.floor(r.height*t),f.style.width=r.width+`px`,f.style.height=r.height+`px`;let i=f.getContext(`2d`);i.setTransform(t,0,0,t,0,0),await e.render({canvasContext:i,viewport:r}).promise;let a=e.getViewport({scale:1}),o=u.clientWidth,s=u.clientHeight;Gg=o>0&&s>0&&a.width>0&&a.height>0?Math.min((o-24)/a.width,(s-24)/a.height):1,Wg=Ug/n,Ug<Gg*1.05&&Ug>Gg*.95&&(Ug=Gg,Wg=Gg/n,Kg=0,qg=0),h(),m();let c=document.getElementById(`pdfPrevPage`),l=document.getElementById(`pdfNextPage`),d=document.getElementById(`pdfPageInput`);c&&(c.disabled=Hg<=1),l&&(l.disabled=Hg>=Vg.numPages),d&&(d.value=Hg)}await v(),u.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;g(Ug+t*Ug,e.clientX,e.clientY)},{passive:!1}),u.addEventListener(`mousedown`,e=>{e.button===0&&(Jg=!0,Yg=e.clientX,Xg=e.clientY,Zg=Kg,Qg=qg,u.style.cursor=`grabbing`,e.preventDefault())}),kh(o,`mousemove`,e=>{Jg&&(Kg=Zg+(e.clientX-Yg),qg=Qg+(e.clientY-Xg),h(),m())}),kh(o,`mouseup`,()=>{Jg&&(Jg=!1,u.style.cursor=Ug>Gg?`grab`:`default`)}),document.getElementById(`pdfPrevPage`).addEventListener(`click`,()=>{Hg>1&&(Hg--,v())}),document.getElementById(`pdfNextPage`).addEventListener(`click`,()=>{Hg<l&&(Hg++,v())}),document.getElementById(`pdfPageInput`).addEventListener(`change`,e=>{let t=parseInt(e.target.value,10);t>=1&&t<=l&&(Hg=t,v())}),document.getElementById(`pdfZoomIn`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(Ug*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomOut`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(Ug/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomFit`).addEventListener(`click`,()=>{Ug=Gg,Kg=0,qg=0,v()}),u.addEventListener(`dblclick`,()=>{Ug=Gg,Kg=0,qg=0,v()}),kh(o,`resize`,()=>{Vg&&v()})}async function n_(t,n){let i=await(await A(async()=>{let{default:t}=await import(`./lib-YwkWjNcC.js`).then(t=>e(t.default,1));return{default:t}},__vite__mapDeps([6,1,7,5]))).default.convertToHtml({arrayBuffer:t},{styleMap:[`p[style-name='Heading 1'] => h1:fresh`,`p[style-name='Heading 2'] => h2:fresh`,`p[style-name='Heading 3'] => h3:fresh`,`r[style-name='Strong'] => strong`,`r[style-name='Emphasis'] => em`]}),a=i.value||`<p>${r(`workspace.documentEmpty`)}</p>`,o=
|
|
1064
|
+
`;let u=document.getElementById(`pdfViewport`),d=document.getElementById(`pdfPan`),f=document.getElementById(`pdfCanvas`),p=document.getElementById(`pdfZoomInfo`);function m(){d.style.transform=`translate(${Kg}px, ${qg}px) scale(${Wg})`,p.textContent=Math.round(Ug*100)+`%`,Jg||(u.style.cursor=Ug>Gg?`grab`:`default`)}function h(){Ug<=Gg&&(Kg=0,qg=0)}function g(e,t,n){let r=Ug;if(Ug=Math.max(.05,Math.min(5,e)),Wg=Ug/e_,t!==void 0&&n!==void 0){let e=u.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=Ug/r;Kg=i-o*(i-Kg),qg=a-o*(a-qg)}h(),m(),_()}function _(){$g&&clearTimeout($g),$g=setTimeout(()=>{v()},180)}async function v(){if(!Vg)return;let e=await Vg.getPage(Hg),t=window.devicePixelRatio||1,n=Math.max(Ug,1);e_=n;let r=e.getViewport({scale:n});f.width=Math.floor(r.width*t),f.height=Math.floor(r.height*t),f.style.width=r.width+`px`,f.style.height=r.height+`px`;let i=f.getContext(`2d`);i.setTransform(t,0,0,t,0,0),await e.render({canvasContext:i,viewport:r}).promise;let a=e.getViewport({scale:1}),o=u.clientWidth,s=u.clientHeight;Gg=o>0&&s>0&&a.width>0&&a.height>0?Math.min((o-24)/a.width,(s-24)/a.height):1,Wg=Ug/n,Ug<Gg*1.05&&Ug>Gg*.95&&(Ug=Gg,Wg=Gg/n,Kg=0,qg=0),h(),m();let c=document.getElementById(`pdfPrevPage`),l=document.getElementById(`pdfNextPage`),d=document.getElementById(`pdfPageInput`);c&&(c.disabled=Hg<=1),l&&(l.disabled=Hg>=Vg.numPages),d&&(d.value=Hg)}await v(),u.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;g(Ug+t*Ug,e.clientX,e.clientY)},{passive:!1}),u.addEventListener(`mousedown`,e=>{e.button===0&&(Jg=!0,Yg=e.clientX,Xg=e.clientY,Zg=Kg,Qg=qg,u.style.cursor=`grabbing`,e.preventDefault())}),kh(o,`mousemove`,e=>{Jg&&(Kg=Zg+(e.clientX-Yg),qg=Qg+(e.clientY-Xg),h(),m())}),kh(o,`mouseup`,()=>{Jg&&(Jg=!1,u.style.cursor=Ug>Gg?`grab`:`default`)}),document.getElementById(`pdfPrevPage`).addEventListener(`click`,()=>{Hg>1&&(Hg--,v())}),document.getElementById(`pdfNextPage`).addEventListener(`click`,()=>{Hg<l&&(Hg++,v())}),document.getElementById(`pdfPageInput`).addEventListener(`change`,e=>{let t=parseInt(e.target.value,10);t>=1&&t<=l&&(Hg=t,v())}),document.getElementById(`pdfZoomIn`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(Ug*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomOut`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(Ug/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomFit`).addEventListener(`click`,()=>{Ug=Gg,Kg=0,qg=0,v()}),u.addEventListener(`dblclick`,()=>{Ug=Gg,Kg=0,qg=0,v()}),kh(o,`resize`,()=>{Vg&&v()})}async function n_(t,n){let i=await(await A(async()=>{let{default:t}=await import(`./lib-YwkWjNcC.js`).then(t=>e(t.default,1));return{default:t}},__vite__mapDeps([6,1,7,5]))).default.convertToHtml({arrayBuffer:t},{styleMap:[`p[style-name='Heading 1'] => h1:fresh`,`p[style-name='Heading 2'] => h2:fresh`,`p[style-name='Heading 3'] => h3:fresh`,`r[style-name='Strong'] => strong`,`r[style-name='Emphasis'] => em`]}),a=i.value||`<p>${r(`workspace.documentEmpty`)}</p>`,o=ke.sanitize(a,{ALLOWED_TAGS:`h1.h2.h3.h4.h5.h6.p.br.strong.em.u.s.a.img.table.thead.tbody.tr.td.th.ul.ol.li.blockquote.pre.code.hr.sup.sub`.split(`.`),ALLOWED_ATTR:[`href`,`src`,`alt`,`title`,`style`]}),s=i.messages?i.messages.filter(e=>e.type===`error`):[];s.length>0?n.innerHTML=`<div class="workspace-preview-docx">${o}<div class="docx-warnings">${s.map(e=>`<div class="docx-warning">⚠ ${Z(e.message)}</div>`).join(``)}</div></div>`:n.innerHTML=`<div class="workspace-preview-docx">${o}</div>`}var r_=[],i_=0,X=1,a_=1,o_=0,s_=0,c_=!1,l_=0,u_=0,d_=0,f_=0;async function p_(e,t,n,i,a){i.dataset.previewType=`pptx`;let{pptxToHtml:o}=await A(async()=>{let{pptxToHtml:e}=await import(`./dist-DuuG_8Br.js`);return{pptxToHtml:e}},__vite__mapDeps([8,1,7]));if(r_=await o(e,{width:960,height:540,scaleToFit:!0,letterbox:!0}),i_=0,X=1,a_=1,o_=0,s_=0,!r_||r_.length===0){n.innerHTML=`<div class="workspace-panel-error">${r(`workspace.pptxEmptyOrFailed`)}</div>`;return}let s=r_.length;document.getElementById(`workspacePreviewLineCount`).textContent=r(`workspace.pageCount`,{count:s}),n.innerHTML=`
|
|
1065
1065
|
<div class="pptx-wrap">
|
|
1066
1066
|
<div class="pptx-toolbar">
|
|
1067
1067
|
<button class="pptx-toolbar-btn" id="pptxPrevSlide" title="${r(`workspace.prevPage`)}" disabled>
|
|
@@ -1090,7 +1090,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1090
1090
|
</div>
|
|
1091
1091
|
</div>
|
|
1092
1092
|
</div>
|
|
1093
|
-
`,g_();let c=document.getElementById(`pptxViewport`),l=document.getElementById(`pptxPan`),u=document.getElementById(`pptxZoomInfo`);function d(){l.style.transform=`translate(${o_}px, ${s_}px) scale(${X})`,u.textContent=Math.round(X*100)+`%`,c_||(c.style.cursor=X>a_?`grab`:`default`)}function f(){X<=a_&&(o_=0,s_=0)}function p(e,t,n){let r=X;if(X=Math.max(.05,Math.min(5,e)),t!==void 0&&n!==void 0){let e=c.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=X/r;o_=i-o*(i-o_),s_=a-o*(a-s_)}X<a_*1.05&&X>a_*.95&&(X=a_,o_=0,s_=0),f(),d()}c.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;p(X+t*X,e.clientX,e.clientY)},{passive:!1}),c.addEventListener(`mousedown`,e=>{e.button===0&&(c_=!0,l_=e.clientX,u_=e.clientY,d_=o_,f_=s_,c.style.cursor=`grabbing`,e.preventDefault())}),kh(a,`mousemove`,e=>{c_&&(o_=d_+(e.clientX-l_),s_=f_+(e.clientY-u_),f(),d())}),kh(a,`mouseup`,()=>{c_&&(c_=!1,c.style.cursor=X>a_?`grab`:`default`)}),document.getElementById(`pptxPrevSlide`).addEventListener(`click`,()=>{i_>0&&(i_--,g_())}),document.getElementById(`pptxNextSlide`).addEventListener(`click`,()=>{i_<s-1&&(i_++,g_())}),document.getElementById(`pptxZoomIn`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(X*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomOut`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(X/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomFit`).addEventListener(`click`,()=>{requestAnimationFrame(()=>{m_(),X=a_,o_=0,s_=0,l.style.transform=`translate(0px, 0px) scale(${a_})`,u.textContent=Math.round(a_*100)+`%`,c.style.cursor=`default`})}),c.addEventListener(`dblclick`,()=>{requestAnimationFrame(()=>{m_(),X=a_,o_=0,s_=0,l.style.transform=`translate(0px, 0px) scale(${a_})`,u.textContent=Math.round(a_*100)+`%`,c.style.cursor=`default`})}),kh(a,`resize`,()=>{!r_||r_.length===0||requestAnimationFrame(()=>{h_()})})}function m_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxSlideContainer`);if(!e||!t)return;let n=parseFloat(t.style.width)||960,r=parseFloat(t.style.height)||540,i=e.clientWidth,a=e.clientHeight;a_=i>0&&a>0&&n>0&&r>0?Math.min((i-8)/n,(a-8)/r):1}function h_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxPan`),n=document.getElementById(`pptxZoomInfo`);if(!e||!t)return;let r=a_;m_(),X<=r*1.05&&(X=a_,o_=0,s_=0),t.style.transform=`translate(${o_}px, ${s_}px) scale(${X})`,n&&(n.textContent=Math.round(X*100)+`%`),c_||(e.style.cursor=X>a_?`grab`:`default`)}function g_(){let e=document.getElementById(`pptxSlideContainer`),t=document.getElementById(`pptxPan`);if(!e||!t||i_<0||i_>=r_.length)return;t.style.transform=`scale(1)`;let n=r_[i_],r=
|
|
1093
|
+
`,g_();let c=document.getElementById(`pptxViewport`),l=document.getElementById(`pptxPan`),u=document.getElementById(`pptxZoomInfo`);function d(){l.style.transform=`translate(${o_}px, ${s_}px) scale(${X})`,u.textContent=Math.round(X*100)+`%`,c_||(c.style.cursor=X>a_?`grab`:`default`)}function f(){X<=a_&&(o_=0,s_=0)}function p(e,t,n){let r=X;if(X=Math.max(.05,Math.min(5,e)),t!==void 0&&n!==void 0){let e=c.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=X/r;o_=i-o*(i-o_),s_=a-o*(a-s_)}X<a_*1.05&&X>a_*.95&&(X=a_,o_=0,s_=0),f(),d()}c.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;p(X+t*X,e.clientX,e.clientY)},{passive:!1}),c.addEventListener(`mousedown`,e=>{e.button===0&&(c_=!0,l_=e.clientX,u_=e.clientY,d_=o_,f_=s_,c.style.cursor=`grabbing`,e.preventDefault())}),kh(a,`mousemove`,e=>{c_&&(o_=d_+(e.clientX-l_),s_=f_+(e.clientY-u_),f(),d())}),kh(a,`mouseup`,()=>{c_&&(c_=!1,c.style.cursor=X>a_?`grab`:`default`)}),document.getElementById(`pptxPrevSlide`).addEventListener(`click`,()=>{i_>0&&(i_--,g_())}),document.getElementById(`pptxNextSlide`).addEventListener(`click`,()=>{i_<s-1&&(i_++,g_())}),document.getElementById(`pptxZoomIn`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(X*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomOut`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(X/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomFit`).addEventListener(`click`,()=>{requestAnimationFrame(()=>{m_(),X=a_,o_=0,s_=0,l.style.transform=`translate(0px, 0px) scale(${a_})`,u.textContent=Math.round(a_*100)+`%`,c.style.cursor=`default`})}),c.addEventListener(`dblclick`,()=>{requestAnimationFrame(()=>{m_(),X=a_,o_=0,s_=0,l.style.transform=`translate(0px, 0px) scale(${a_})`,u.textContent=Math.round(a_*100)+`%`,c.style.cursor=`default`})}),kh(a,`resize`,()=>{!r_||r_.length===0||requestAnimationFrame(()=>{h_()})})}function m_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxSlideContainer`);if(!e||!t)return;let n=parseFloat(t.style.width)||960,r=parseFloat(t.style.height)||540,i=e.clientWidth,a=e.clientHeight;a_=i>0&&a>0&&n>0&&r>0?Math.min((i-8)/n,(a-8)/r):1}function h_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxPan`),n=document.getElementById(`pptxZoomInfo`);if(!e||!t)return;let r=a_;m_(),X<=r*1.05&&(X=a_,o_=0,s_=0),t.style.transform=`translate(${o_}px, ${s_}px) scale(${X})`,n&&(n.textContent=Math.round(X*100)+`%`),c_||(e.style.cursor=X>a_?`grab`:`default`)}function g_(){let e=document.getElementById(`pptxSlideContainer`),t=document.getElementById(`pptxPan`);if(!e||!t||i_<0||i_>=r_.length)return;t.style.transform=`scale(1)`;let n=r_[i_],r=ke.sanitize(n,{ALLOWED_TAGS:`div.span.p.a.img.svg.path.circle.rect.line.polyline.polygon.ellipse.g.defs.linearGradient.radialGradient.stop.text.tspan.table.thead.tbody.tr.td.th.br.h1.h2.h3.h4.h5.h6.ul.ol.li.strong.em.b.i.u`.split(`.`),ALLOWED_ATTR:`class.style.id.src.alt.width.height.href.target.d.fill.stroke.stroke-width.transform.viewBox.x.y.cx.cy.r.rx.ry.x1.y1.x2.y2.points.opacity.font-size.font-family.text-anchor.dominant-baseline.clip-path.preserveAspectRatio.xmlns`.split(`.`)});e.style.width=``,e.style.height=``,e.innerHTML=r;let i=e.firstElementChild;i?(e.style.width=(i.offsetWidth||960)+`px`,e.style.height=(i.offsetHeight||540)+`px`):(e.style.width=`960px`,e.style.height=`540px`),m_(),X=a_,o_=0,s_=0,t.style.transform=`translate(0px, 0px) scale(${a_})`;let a=document.getElementById(`pptxZoomInfo`);a&&(a.textContent=Math.round(X*100)+`%`);let o=document.getElementById(`pptxViewport`);o&&!c_&&(o.style.cursor=`default`);let s=document.getElementById(`pptxPrevSlide`),c=document.getElementById(`pptxNextSlide`),l=document.getElementById(`pptxSlideNum`);s&&(s.disabled=i_<=0),c&&(c.disabled=i_>=r_.length-1),l&&(l.textContent=i_+1)}var __=[],v_=0;async function y_(e,t,n){t.innerHTML=`<div class="workspace-panel-empty">${r(`workspace.parsingExcel`)}</div>`;let i=n.dataset.previewPath,a;try{let e=await jt();if(!e)throw Error(r(`workspace.agentNotPaired`));a=await(await fetch(`${e.url}/api/fs/preview-xlsx`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(e)},body:JSON.stringify({path:i,maxRows:500})})).json()}catch(e){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.requestFailed`,{error:Z(e.message)})}</div>`;return}if(!a.success){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.parseFailed`,{error:Z(a.error||r(`workspace.unknownError`))})}</div>`;return}let{sheets:o}=a.data;if(!o||o.length===0){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.noSheetsInWorkbook`)}</div>`;return}__=o,v_=0,n.dataset.previewType=`xlsx`,n.dataset.previewSheets=JSON.stringify(o.map(e=>e.name)),t.classList.add(`xlsx-mode`);let s=`<div class="xlsx-sheet-tabs" id="xlsxSheetTabs">`;o.forEach((e,t)=>{s+=`<button class="xlsx-sheet-tab${t===0?` active`:``}" data-sheet="${t}">${Z(e.name)}</button>`}),s+=`</div>`,t.innerHTML=s+`<div class="xlsx-sheet-content" id="xlsxSheetContent"><div class="workspace-panel-empty">${r(`workspace.loadingData`)}</div></div>`,document.getElementById(`xlsxSheetTabs`).addEventListener(`click`,e=>{let t=e.target.closest(`.xlsx-sheet-tab`);if(!t)return;let n=parseInt(t.dataset.sheet,10);n!==v_&&(document.querySelectorAll(`.xlsx-sheet-tab`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`),b_(n))}),await b_(0)}async function b_(e){let t=document.getElementById(`xlsxSheetContent`);if(!t)return;v_=e;let n=__[e];if(!n){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.sheetNotFound`)}</div>`;return}x_(n.rows,n.colCount,n.totalRows,t)}function x_(e,t,n,i){let a=i.querySelector(`.xlsx-table-scrollbar-mirror`);if(a&&a.remove(),!e||e.length===0){i.innerHTML=`<div class="workspace-panel-empty">${r(`workspace.emptySheet`)}</div>`;return}let o=e[0],s=`<div class="xlsx-table-scroll" id="xlsxTableScroll"><table class="xlsx-preview-table"><thead><tr>`;for(let e of o)s+=`<th>${Z(String(e??``))}</th>`;s+=`</tr></thead><tbody>`;for(let n=1;n<e.length;n++){s+=`<tr>`;for(let r=0;r<t;r++)s+=`<td>${Z(String(e[n][r]??``))}</td>`;s+=`</tr>`}s+=`</tbody></table></div>`,n>Rg&&(s+=`<div class="xlsx-truncated-msg">${r(`workspace.xlsxTruncatedHint`,{shown:Rg,total:n})}</div>`),i.innerHTML=s;let c=i.querySelector(`#xlsxTableScroll`);if(c){let e=document.createElement(`div`);e.className=`xlsx-table-scrollbar-mirror`,e.innerHTML=`<div class="xlsx-table-scrollbar-mirror-inner" style="width:${c.scrollWidth}px;"></div>`;let t=!1;c.addEventListener(`scroll`,()=>{if(t){t=!1;return}t=!0,e.scrollLeft=c.scrollLeft}),e.addEventListener(`scroll`,()=>{if(t){t=!1;return}t=!0,c.scrollLeft=e.scrollLeft}),i.appendChild(e)}}async function S_(e,t,n,i){let a={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,bmp:`image/bmp`,ico:`image/x-icon`}[(t.split(`.`).pop()||``).toLowerCase()]||`image/png`,o=new Blob([e],{type:a}),s=URL.createObjectURL(o);n.innerHTML=`
|
|
1094
1094
|
<div class="image-preview-wrap">
|
|
1095
1095
|
<div class="image-preview-toolbar">
|
|
1096
1096
|
<button class="image-preview-btn" id="imgZoomOut" title="${r(`workspace.zoomOut`)}">
|
|
@@ -1124,14 +1124,14 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1124
1124
|
<source src="${c}" type="${Z(o)}">
|
|
1125
1125
|
</audio>
|
|
1126
1126
|
<div id="mediaUnsupportedHint" style="display:none;">${u}</div>
|
|
1127
|
-
</div>`;let d=i.querySelector(`video, audio`),f=i.querySelector(`#mediaUnsupportedHint`);if(d){let e=()=>{d.style.display=`none`,f&&(f.style.display=`block`)};d.addEventListener(`error`,e),i.querySelectorAll(`source`).forEach(t=>t.addEventListener(`error`,e))}}var T_=!1;function E_(e,t){let n=e.getBoundingClientRect();t.style.top=n.bottom+4+`px`;let r=n.right-160;t.style.left=Math.max(4,r)+`px`,t.style.right=`auto`}function D_(e,t){E_(e,t),t.classList.add(`show`)}function O_(){let e=document.getElementById(`workspacePreviewExportMenu`),t=document.getElementById(`workspacePreviewExportBtn`),n=document.getElementById(`workspacePreviewExportDropdown`);if(!e||!t||!n)return;document.body.appendChild(n),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.contains(`show`)?n.classList.remove(`show`):D_(t,n)});let r=null,i=null;e.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null),r=setTimeout(()=>{D_(t,n)},200)}),e.addEventListener(`mouseleave`,()=>{r&&=(clearTimeout(r),null),i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},300)}),n.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null)}),n.addEventListener(`mouseleave`,()=>{i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},200)}),n.querySelectorAll(`.ws-export-dropdown-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let r=e.dataset.exportType;n.classList.remove(`show`),A_(r)})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&!n.contains(t.target)&&n.classList.remove(`show`)});let a=()=>{n.classList.contains(`show`)&&E_(t,n)};document.getElementById(`workspacePreviewContent`)?.addEventListener(`scroll`,a),window.addEventListener(`resize`,a)}function k_(){return document.getElementById(`workspacePreviewArea`).dataset.markdownText||``}async function A_(e){if(T_)return;T_=!0;let t=document.getElementById(`workspacePreviewExportBtn`);document.getElementById(`workspacePreviewExportMenu`);let n=document.getElementById(`workspacePreviewExportDropdown`),a=document.getElementById(`workspacePreviewArea`).dataset.previewName||`export`,o=t.innerHTML;t.innerHTML=`<svg viewBox="0 0 24 24" fill="none" style="animation: spin 0.8s linear infinite; width: 14px; height: 14px; flex-shrink: 0;"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10" opacity="0.25"/><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10"/></svg>`,t.disabled=!0,t.style.opacity=`0.6`;try{switch(e){case`docx`:await N_(a);break;case`pdf`:await F_(a);break;case`image`:await I_(a);break;case`md`:L_(a);break}}catch(e){i.error(`[WorkspacePanel] export failed:`,e),
|
|
1127
|
+
</div>`;let d=i.querySelector(`video, audio`),f=i.querySelector(`#mediaUnsupportedHint`);if(d){let e=()=>{d.style.display=`none`,f&&(f.style.display=`block`)};d.addEventListener(`error`,e),i.querySelectorAll(`source`).forEach(t=>t.addEventListener(`error`,e))}}var T_=!1;function E_(e,t){let n=e.getBoundingClientRect();t.style.top=n.bottom+4+`px`;let r=n.right-160;t.style.left=Math.max(4,r)+`px`,t.style.right=`auto`}function D_(e,t){E_(e,t),t.classList.add(`show`)}function O_(){let e=document.getElementById(`workspacePreviewExportMenu`),t=document.getElementById(`workspacePreviewExportBtn`),n=document.getElementById(`workspacePreviewExportDropdown`);if(!e||!t||!n)return;document.body.appendChild(n),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.contains(`show`)?n.classList.remove(`show`):D_(t,n)});let r=null,i=null;e.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null),r=setTimeout(()=>{D_(t,n)},200)}),e.addEventListener(`mouseleave`,()=>{r&&=(clearTimeout(r),null),i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},300)}),n.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null)}),n.addEventListener(`mouseleave`,()=>{i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},200)}),n.querySelectorAll(`.ws-export-dropdown-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let r=e.dataset.exportType;n.classList.remove(`show`),A_(r)})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&!n.contains(t.target)&&n.classList.remove(`show`)});let a=()=>{n.classList.contains(`show`)&&E_(t,n)};document.getElementById(`workspacePreviewContent`)?.addEventListener(`scroll`,a),window.addEventListener(`resize`,a)}function k_(){return document.getElementById(`workspacePreviewArea`).dataset.markdownText||``}async function A_(e){if(T_)return;T_=!0;let t=document.getElementById(`workspacePreviewExportBtn`);document.getElementById(`workspacePreviewExportMenu`);let n=document.getElementById(`workspacePreviewExportDropdown`),a=document.getElementById(`workspacePreviewArea`).dataset.previewName||`export`,o=t.innerHTML;t.innerHTML=`<svg viewBox="0 0 24 24" fill="none" style="animation: spin 0.8s linear infinite; width: 14px; height: 14px; flex-shrink: 0;"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10" opacity="0.25"/><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10"/></svg>`,t.disabled=!0,t.style.opacity=`0.6`;try{switch(e){case`docx`:await N_(a);break;case`pdf`:await F_(a);break;case`image`:await I_(a);break;case`md`:L_(a);break}}catch(e){i.error(`[WorkspacePanel] export failed:`,e),P(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{T_=!1,t.innerHTML=o,t.disabled=!1,t.style.opacity=`1`,n.classList.remove(`show`)}}async function j_(e){if(typeof mermaid>`u`)return;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await A(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-DZntnUPd.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([9,10,1,11,2,3,12,0]));await t(e),await n(e)}async function M_(e){if(typeof mermaid>`u`||!/```mermaid/i.test(e))return e;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await A(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-DZntnUPd.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([9,10,1,11,2,3,12,0]));try{let r=et(e),i=document.createElement(`div`);i.style.cssText=`position:fixed;left:-9999px;top:-9999px;`,i.innerHTML=r,document.body.appendChild(i),await t(i),await n(i);let a=i.querySelectorAll(`.mermaid`),o=[];for(let e of a){let t=e.querySelector(`img`);t&&t.src&&t.src.startsWith(`data:`)?o.push(t.src):o.push(null)}if(document.body.removeChild(i),o.length===0)return e;let s=0;return e.replace(/```\s*mermaid\s*[\r\n]+([\s\S]*?)```/gi,e=>{let t=o[s];return s++,t?``:e})}catch(t){return i.warn(`[WorkspacePanel] Mermaid pre-render failed:`,t.message),e}}async function N_(e){let{Packer:t}=await A(async()=>{let{Packer:e}=await import(`./dist-BUuoW_84.js`);return{Packer:e}},__vite__mapDeps([10,1])),{createDocxDocument:n}=await A(async()=>{let{createDocxDocument:e}=await import(`./chat-export-DZntnUPd.js`);return{createDocxDocument:e}},__vite__mapDeps([9,10,1,11,2,3,12,0])),i=k_();if(!i){P(r(`chatExport.noContent`),`error`);return}i=await M_(i);let a=n(await P_(i)),o=await t.toBlob(a),s=`word-${new Date().getTime()}.docx`;R_(o,s),P(r(`workspace.downloaded`,{name:s}),`success`)}async function P_(e){let{Document:t,Packer:n,Paragraph:r,TextRun:i,HeadingLevel:a,Table:o,TableRow:s,TableCell:c,AlignmentType:l,WidthType:u,BorderStyle:d,ImageRun:f,ExternalHyperlink:p,convertInchesToTwip:m}=await A(async()=>{let{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}=await import(`./dist-BUuoW_84.js`);return{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}},__vite__mapDeps([10,1])),{createTextRuns:h,sanitizeDocxText:g,nextDocxImageId:_,isDocxEmbeddableImageType:v}=await A(async()=>{let{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}=await import(`./chat-export-DZntnUPd.js`);return{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}},__vite__mapDeps([9,10,1,11,2,3,12,0]));if(!e||!e.trim())return[new r({children:[new i({text:``})]})];let y=[],b=g(e),x=[];b=b.replace(/```(\w*)\n([\s\S]*?)```/g,(e,t,n)=>{let r=x.length;return x.push({lang:t||``,code:n.trimEnd()}),`\n\n%%CODEBLOCK_${r}%%\n\n`});let S=[];b=b.replace(/<table[\s\S]*?<\/table>/gi,e=>{let t=S.length;return S.push(e),`\n\n%%HTMLTABLE_${t}%%\n\n`});let C=[];b=b.replace(/(?:^\|.+\|\s*$\n)+^\|[\s\-:|]+\|\s*$\n(?:^\|.+\|\s*$\n?)+/gm,e=>{let t=C.length;return C.push(e),`\n\n%%MDTABLE_${t}%%\n\n`});let w=b.split(/\n{2,}/).filter(e=>e.trim());function T(e){if(!e)return[];let t=/(\*\*(.+?)\*\*|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)|__(.+?)__|(?<!_)_(?!_)(.+?)(?<!_)_(?!_)|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)|!\[([^\]]*)\]\(([^)]+)\))/,n=[],r=e;for(;r.length>0;){let e=r.match(t);if(!e){n.push(...h(r));break}let a=e.index;a>0&&n.push(...h(r.slice(0,a)));let o=e[1];if(e[2]!==void 0)n.push(...h(e[2],{bold:!0}));else if(e[3]!==void 0)n.push(...h(e[3],{italics:!0}));else if(e[4]!==void 0)n.push(...h(e[4],{bold:!0}));else if(e[5]!==void 0)n.push(...h(e[5],{italics:!0}));else if(e[6]!==void 0)n.push(new i({text:e[6],font:`Consolas`,size:20}));else if(e[7]!==void 0)n.push(new p({children:[new i({text:e[7],style:`Hyperlink`})],link:e[8]}));else if(e[9]!==void 0){let t=e[10];if(t.startsWith(`data:`))try{let[r,a]=t.split(`,`),o=r.match(/data:(image\/(\w+))/);if(o&&a&&v(o[2])){let t=atob(a),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);n.push(new f({data:r,transformation:{width:400,height:300},type:o[2],altText:{id:_(),name:e[9]||`image`}}))}else n.push(new i({text:`[Image: `+(e[9]||`image`)+`]`,italics:!0,color:`999999`}))}catch{n.push(new i({text:`[Image]`,italics:!0,color:`999999`}))}else n.push(new i({text:`[Image: `+(e[9]||t)+`]`,italics:!0,color:`999999`}))}r=r.slice(a+o.length)}return n}function E(e){let t=new DOMParser().parseFromString(e,`text/html`),n=[];return t.querySelectorAll(`tr`).forEach(e=>{let t=[];e.querySelectorAll(`th, td`).forEach(e=>t.push(e.textContent.trim())),t.length>0&&n.push(t)}),n}function D(e){let t=e.trim().split(`
|
|
1128
1128
|
`),n=[];for(let e of t){if(/^[\s\|:\-]+$/.test(e.replace(/\|/g,``)))continue;let t=Xe(e).slice(1,-1).map(e=>e.trim());t.length>0&&n.push(t)}return n}function O(e){if(e.length===0)return new r({children:[]});let t=Math.max(...e.map(e=>e.length));return new o({rows:e.map((e,n)=>{let i=[];for(let a=0;a<t;a++){let o=e[a]||``;i.push(new c({children:[new r({children:T(o),spacing:{before:40,after:40}})],shading:n===0?{fill:`F2F2F2`}:void 0,width:{size:Math.round(100/t*100)/100,type:u.PERCENTAGE}}))}return new s({children:i})}),width:{size:100,type:u.PERCENTAGE},borders:{top:{style:d.SINGLE,size:1,color:`DDDDDD`},bottom:{style:d.SINGLE,size:1,color:`DDDDDD`},left:{style:d.SINGLE,size:1,color:`DDDDDD`},right:{style:d.SINGLE,size:1,color:`DDDDDD`},insideHorizontal:{style:d.SINGLE,size:1,color:`DDDDDD`},insideVertical:{style:d.SINGLE,size:1,color:`DDDDDD`}}})}for(let e of w){let t=e.trim(),n=t.match(/^%%CODEBLOCK_(\d+)%%$/);if(n){let{lang:e,code:t}=x[parseInt(n[1])],a=e?`${e} code`:`code`;y.push(new r({children:[new i({text:a,bold:!0,font:`Consolas`,size:18})]}));let o=t.split(`
|
|
1129
1129
|
`);for(let e of o)y.push(new r({children:[new i({text:e||` `,font:`Consolas`,size:18})],spacing:{before:0,after:0,line:240},shading:{fill:`F5F5F5`}}));y.push(new r({children:[new i({text:``})]}));continue}let o=t.match(/^%%HTMLTABLE_(\d+)%%$/);if(o){let e=E(S[parseInt(o[1])]);e.length>0&&(y.push(O(e)),y.push(new r({children:[new i({text:``})]})));continue}let s=t.match(/^%%MDTABLE_(\d+)%%$/);if(s){let e=D(C[parseInt(s[1])]);y.push(O(e)),y.push(new r({children:[new i({text:``})]}));continue}let c=t.match(/^(#{1,6})\s+(.+)/);if(c){let e={1:a.HEADING_1,2:a.HEADING_2,3:a.HEADING_3,4:a.HEADING_4,5:a.HEADING_5,6:a.HEADING_6};y.push(new r({children:T(c[2]),heading:e[c[1].length]||a.HEADING_1,border:{bottom:{style:d.SINGLE,size:6,color:`EAECEF`}}}));let n=t.slice(c[0].length).replace(/^\n+/,``).trim();n&&y.push(new r({children:T(n),spacing:{before:60,after:60}}));continue}if(/^(---|\*\*\*|___)\s*$/.test(t)){y.push(new r({children:[],border:{bottom:{style:d.SINGLE,size:6,color:`CCCCCC`}},spacing:{before:200,after:200}}));continue}if(/^[\-\*\+]\s+/.test(t)){let t=e.split(/\n(?=[\-\*\+]\s+)/);for(let e of t)y.push(new r({children:T(e.replace(/^[\-\*\+]\s+/,``)),bullet:{level:0},spacing:{before:40,after:40}}));continue}if(/^\d+\.\s+/.test(t)){let t=e.split(/\n(?=\d+\.\s+)/);for(let e of t)y.push(new r({children:T(e.replace(/^\d+\.\s+/,``)),numbering:{reference:`default`,level:0},spacing:{before:40,after:40}}));continue}if(t.startsWith(`>`)){let t=e.split(`
|
|
1130
1130
|
`).map(e=>e.replace(/^>\s?/,``)).join(`
|
|
1131
|
-
`);y.push(new r({children:T(t),indent:{left:m(.5)},border:{left:{style:d.SINGLE,size:12,color:`CCCCCC`}},spacing:{before:60,after:60}}));continue}let l=T(t);y.push(new r({children:l.length>0?l:h(t),spacing:{before:60,after:60}}))}return y}async function F_(e){let{jsPDF:t,html2canvas:n}=await
|
|
1131
|
+
`);y.push(new r({children:T(t),indent:{left:m(.5)},border:{left:{style:d.SINGLE,size:12,color:`CCCCCC`}},spacing:{before:60,after:60}}));continue}let l=T(t);y.push(new r({children:l.length>0?l:h(t),spacing:{before:60,after:60}}))}return y}async function F_(e){let{jsPDF:t,html2canvas:n}=await Pe();if(!t||!n){P(r(`chatExport.pdfLibNotLoaded`),`error`);return}let a=k_();if(!a){P(r(`chatExport.noContent`),`error`);return}let o=document.createElement(`div`);o.style.cssText=`position:fixed;left:-9999px;top:-9999px;width:515px;padding:40px;background:white;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB','Microsoft YaHei',sans-serif;font-size:12px;line-height:1.6;color:#333;box-sizing:border-box;`,o.innerHTML=`<div class="markdown-body">${et(a)}</div>`,document.body.appendChild(o),await j_(o);let s=o.scrollHeight,c=Math.ceil(s/762);n(o,{scale:2,useCORS:!0,logging:!1,backgroundColor:`#ffffff`,willReadFrequently:!0}).then(e=>{let n=new t({orientation:`portrait`,unit:`px`,format:[595,842],compress:!0}),i=e.width,a=e.height,l=a/s,u=762*l;for(let t=0;t<c;t++){t>0&&n.addPage();let r=t*u,o=Math.min(r+u,a)-r,s=document.createElement(`canvas`);s.width=i,s.height=o;let c=s.getContext(`2d`,{willReadFrequently:!0});c.fillStyle=`#ffffff`,c.fillRect(0,0,s.width,s.height),c.drawImage(e,0,r,i,o,0,0,i,o);let d,f;try{d=s.toDataURL(`image/jpeg`,.85),f=`JPEG`}catch{d=s.toDataURL(`image/png`),f=`PNG`}let p=o/l;n.addImage(d,f,0,0,595,p,void 0,`FAST`)}let d=`pdf-${new Date().getTime()}.pdf`;n.save(d),document.body.removeChild(o),P(r(`workspace.downloaded`,{name:d}),`success`)}).catch(e=>{i.error(`[WorkspacePanel] PDF export failed:`,e),P(r(`chatExport.exportFailed`,{message:e.message}),`error`),document.body.removeChild(o)})}async function I_(e){let t=await Ue();if(!t){P(r(`chatExport.imageLibNotLoaded`),`error`);return}let n=document.getElementById(`workspacePreviewContent`).querySelector(`.workspace-preview-markdown`);if(!n){P(r(`chatExport.noContent`),`error`);return}let a=n.cloneNode(!0),o=document.createElement(`div`);o.style.cssText=`position:fixed;left:-9999px;top:-9999px;width:800px;padding:40px;background:white;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;font-size:14px;line-height:1.6;color:#333;box-sizing:border-box;`,o.appendChild(a),document.body.appendChild(o),await j_(o),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e)));try{let e=(await t(o,{scale:2,useCORS:!0,logging:!1,backgroundColor:`#ffffff`,willReadFrequently:!0})).toDataURL(`image/jpeg`,.92),n=document.createElement(`a`);n.href=e;let i=`image-${new Date().getTime()}.jpg`;n.download=i,document.body.appendChild(n),n.click(),document.body.removeChild(n),P(r(`workspace.downloaded`,{name:i}),`success`)}catch(e){i.error(`[WorkspacePanel] image export failed:`,e),P(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{document.body.removeChild(o)}}function L_(e){let t=k_();if(!t){P(r(`chatExport.noContent`),`error`);return}let n=t.replace(/\r\n/g,`
|
|
1132
1132
|
`).replace(/\n{3,}/g,`
|
|
1133
1133
|
|
|
1134
|
-
`),i=new Blob([n],{type:`text/markdown;charset=utf-8`}),a=`md-${new Date().getTime()}.md`;R_(i,a),
|
|
1134
|
+
`),i=new Blob([n],{type:`text/markdown;charset=utf-8`}),a=`md-${new Date().getTime()}.md`;R_(i,a),P(r(`workspace.downloaded`,{name:a}),`success`)}function R_(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}async function z_(e){let t=document.getElementById(`workspacePreviewArea`),n=t.dataset.previewPath;if(!n)return;if((t.dataset.previewType||Dt(t.dataset.previewName||``))!==`text`){P(r(`workspace.copyUnsupportedType`),`info`);return}let i=e&&(e.ctrlKey||e.metaKey),a=document.getElementById(`workspacePreviewContent`).classList.contains(`markdown-rendered`);if(i&&a)await B_();else{let e=t.dataset.markdownText||t.dataset.htmlText||``;if(e)try{await navigator.clipboard.writeText(e),P(r(`workspace.copiedToClipboard`),`success`)}catch{P(r(`workspace.copyFailedManual`),`error`)}else{let e=await qt(n);if(e.success)try{await navigator.clipboard.writeText(e.content||``),P(r(`workspace.copiedToClipboard`),`success`)}catch{P(r(`workspace.copyFailedManual`),`error`)}else P(r(`workspace.getContentFailed`),`error`)}}}async function B_(){let e=document.getElementById(`workspacePreviewContent`).querySelector(`.workspace-preview-markdown`);if(!e){P(r(`chatCopy.copyFailedManual`),`error`);return}let t=e.cloneNode(!0);t.querySelectorAll(`table`).forEach(e=>{let t=it(e);e.parentNode.replaceChild(t,e)});let n=t.innerHTML,a=t.textContent||``,o=V_(n);try{if(typeof ClipboardItem<`u`){let e=new ClipboardItem({"text/plain":new Blob([a],{type:`text/plain`}),"text/html":new Blob([o],{type:`text/html`})});await navigator.clipboard.write([e])}else{let e=document.createElement(`div`);e.style.position=`fixed`,e.style.left=`-999999px`,e.style.top=`-999999px`,e.innerHTML=o,document.body.appendChild(e);let t=document.createRange();t.selectNodeContents(e);let n=window.getSelection();n.removeAllRanges(),n.addRange(t);try{document.execCommand(`copy`)}catch{await navigator.clipboard.writeText(a)}finally{n.removeAllRanges(),document.body.removeChild(e)}}P(r(`chatCopy.copiedRich`),`success`)}catch(e){i.warn(`[WorkspacePanel] rich textcopy failed:`,e.message);try{await navigator.clipboard.writeText(a),P(r(`workspace.copiedToClipboard`),`success`)}catch{P(r(`workspace.copyFailedManual`),`error`)}}}function V_(e){return`<!DOCTYPE html><html><head>
|
|
1135
1135
|
<style>
|
|
1136
1136
|
h1 { font-size: 24px; font-weight: bold; margin: 16px 0 8px; }
|
|
1137
1137
|
h2 { font-size: 20px; font-weight: bold; margin: 14px 0 6px; }
|
|
@@ -1152,17 +1152,17 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1152
1152
|
a { color: #007bff; text-decoration: underline; }
|
|
1153
1153
|
img { max-width: 100%; }
|
|
1154
1154
|
</style>
|
|
1155
|
-
</head><body>${e}</body></html>`}async function H_(){let e=document.getElementById(`workspacePreviewArea`),t=e.dataset.previewPath,n=e.dataset.previewName;t&&await av(t,n)}async function U_(){let e=document.getElementById(`workspacePreviewArea`).dataset.previewPath;if(e)try{let t=await Ot(e);if(!t.success){
|
|
1155
|
+
</head><body>${e}</body></html>`}async function H_(){let e=document.getElementById(`workspacePreviewArea`),t=e.dataset.previewPath,n=e.dataset.previewName;t&&await av(t,n)}async function U_(){let e=document.getElementById(`workspacePreviewArea`).dataset.previewPath;if(e)try{let t=await Ot(e);if(!t.success){P(r(`workspace.requestFailed`,{error:t.error}),`error`);return}let n=URL.createObjectURL(t.blob);window.open(n,`_blank`),setTimeout(()=>URL.revokeObjectURL(n),6e4),P(r(`workspace.openInBrowser`),`success`)}catch(e){P(r(`workspace.openFailed`,{error:e.message}),`error`)}}function W_(e,t){let n=e.querySelector(`.workspace-preview-md-icon-preview`),r=e.querySelector(`.workspace-preview-md-icon-source`);n&&(n.style.display=t?`none`:``),r&&(r.style.display=t?``:`none`)}function G_(e){let t=e.trim();if(/^\s*<!DOCTYPE\s/i.test(t)||/^\s*<html[\s>]/i.test(t)){if(/<\/body>/i.test(t)){let e=t.replace(/<\/head>/i,`<style>html,body{overflow:auto!important;height:auto!important;}</style></head>`);return e=e.replace(/<\/body>/i,`<script>(function(){var s=document.createElement('style');s.textContent='.aih-broken-resp{display:inline-flex;align-items:center;justify-content:center;min-width:60px;min-height:40px;background:#f0f0f0;border:1px dashed #ccc;border-radius:4px;color:#999;font-size:12px;padding:4px 8px;}';document.head.appendChild(s);function mark(el){if(el.dataset.aihBroken)return;el.dataset.aihBroken='1';var ph=document.createElement('span');ph.className='aih-broken-resp';ph.textContent='资源未加载';if(el.tagName==='IMG'){el.style.display='none';el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}else if(el.tagName==='LINK'){el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}}document.querySelectorAll('img').forEach(function(img){if(img.complete&&img.naturalWidth===0)mark(img);img.addEventListener('error',function(){mark(img);});});document.addEventListener('error',function(e){var t=e.target;if(t&&(t.tagName==='IMG'||t.tagName==='LINK'||t.tagName==='SCRIPT'))mark(t);},true);})();<\/script></body>`),e}else if(/<\/head>/i.test(t))return t.replace(/<\/head>/i,`<style>html,body{overflow:auto!important;height:auto!important;}</style><script>(function(){var s=document.createElement('style');s.textContent='.aih-broken-resp{display:inline-flex;align-items:center;justify-content:center;min-width:60px;min-height:40px;background:#f0f0f0;border:1px dashed #ccc;border-radius:4px;color:#999;font-size:12px;padding:4px 8px;}';document.head.appendChild(s);function mark(el){if(el.dataset.aihBroken)return;el.dataset.aihBroken='1';var ph=document.createElement('span');ph.className='aih-broken-resp';ph.textContent='资源未加载';if(el.tagName==='IMG'){el.style.display='none';el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}else if(el.tagName==='LINK'){el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}}document.querySelectorAll('img').forEach(function(img){if(img.complete&&img.naturalWidth===0)mark(img);img.addEventListener('error',function(){mark(img);});});document.addEventListener('error',function(e){var t=e.target;if(t&&(t.tagName==='IMG'||t.tagName==='LINK'||t.tagName==='SCRIPT'))mark(t);},true);})();<\/script></head>`);else if(/<body[\s>]/i.test(t))return t.replace(/<body([\s>])/i,`<body$1<style>html,body{overflow:auto!important;height:auto!important;}</style><script>(function(){var s=document.createElement('style');s.textContent='.aih-broken-resp{display:inline-flex;align-items:center;justify-content:center;min-width:60px;min-height:40px;background:#f0f0f0;border:1px dashed #ccc;border-radius:4px;color:#999;font-size:12px;padding:4px 8px;}';document.head.appendChild(s);function mark(el){if(el.dataset.aihBroken)return;el.dataset.aihBroken='1';var ph=document.createElement('span');ph.className='aih-broken-resp';ph.textContent='资源未加载';if(el.tagName==='IMG'){el.style.display='none';el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}else if(el.tagName==='LINK'){el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}}document.querySelectorAll('img').forEach(function(img){if(img.complete&&img.naturalWidth===0)mark(img);img.addEventListener('error',function(){mark(img);});});document.addEventListener('error',function(e){var t=e.target;if(t&&(t.tagName==='IMG'||t.tagName==='LINK'||t.tagName==='SCRIPT'))mark(t);},true);})();<\/script>`);return t}return`<!DOCTYPE html>
|
|
1156
1156
|
<html>
|
|
1157
1157
|
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
|
|
1158
1158
|
<body style="margin:0;padding:0;overflow:auto;">${t}<script>(function(){var s=document.createElement('style');s.textContent='.aih-broken-resp{display:inline-flex;align-items:center;justify-content:center;min-width:60px;min-height:40px;background:#f0f0f0;border:1px dashed #ccc;border-radius:4px;color:#999;font-size:12px;padding:4px 8px;}';document.head.appendChild(s);function mark(el){if(el.dataset.aihBroken)return;el.dataset.aihBroken='1';var ph=document.createElement('span');ph.className='aih-broken-resp';ph.textContent='资源未加载';if(el.tagName==='IMG'){el.style.display='none';el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}else if(el.tagName==='LINK'){el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}}document.querySelectorAll('img').forEach(function(img){if(img.complete&&img.naturalWidth===0)mark(img);img.addEventListener('error',function(){mark(img);});});document.addEventListener('error',function(e){var t=e.target;if(t&&(t.tagName==='IMG'||t.tagName==='LINK'||t.tagName==='SCRIPT'))mark(t);},true);})();<\/script></body>
|
|
1159
1159
|
</html>`}function K_(e,t){let n=G_(t),r=document.createElement(`iframe`);r.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups`),r.setAttribute(`srcdoc`,n),r.className=`workspace-html-preview-frame`,e.innerHTML=``,e.appendChild(r)}function q_(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePreviewFullscreenBtn`),i=e.classList.toggle(`fullscreen`);if(Nn(),i)t.classList.add(`preview-fullscreen`),n.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14"><path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"/></svg>`,n.title=r(`workspace.exitFullscreen`);else{t.classList.remove(`preview-fullscreen`),n.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>`,n.title=r(`workspace.fullscreenPreview`);let e=document.getElementById(`workspacePreviewRail`);e&&e.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}}function J_(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePreviewContent`),n=document.getElementById(`workspacePreviewMdToggleBtn`),i=document.getElementById(`workspacePreviewLineCount`),a=document.getElementById(`workspacePreviewCopyBtn`),o=document.getElementById(`workspacePreviewDownloadBtn`),s=document.getElementById(`workspacePreviewExportMenu`),c=document.getElementById(`workspacePreviewOpenBrowserBtn`),l=e.dataset.previewMode||`markdown`;Nn();let u=t.classList.toggle(`markdown-rendered`);if(l===`html`){let l=e.dataset.htmlText||``;if(u)n.classList.add(`active`),n.title=r(`workspace.switchToSourcePreview`),W_(n,!0),a.style.display=``,o&&(o.style.display=`none`),s&&(s.style.display=`none`),c&&(c.style.display=``),i.textContent=``,K_(t,l);else{n.classList.remove(`active`),n.title=r(`workspace.switchToRenderPreview`),W_(n,!1),a.style.display=``,o&&(o.style.display=``),s&&(s.style.display=`none`),c&&(c.style.display=`none`);let u=kv(e.dataset.previewName||``),d=l.split(`
|
|
1160
1160
|
`);i.textContent=r(`workspace.lineCount`,{count:d.length});let f=`<table class="workspace-preview-code-table"><tbody>`;for(let e=0;e<d.length;e++)f+=`<tr><td class="line-num">${e+1}</td><td class="line-content"><code class="${u}">${Z(d[e])}</code></td></tr>`;f+=`</tbody></table>`,t.innerHTML=f}}else{let c=e.dataset.markdownText||``;if(u)n.classList.add(`active`),n.title=r(`workspace.switchToSourcePreview`),W_(n,!0),a.style.display=``,o&&(o.style.display=`none`),s&&(s.style.display=``),t.innerHTML=`<div class="markdown-body workspace-preview-markdown">${et(c)}</div>`,X_(t),Z_(t),Ze(),i.textContent=``;else{n.classList.remove(`active`),n.title=r(`workspace.switchToRenderPreview`),W_(n,!1),a.style.display=``,o&&(o.style.display=``),s&&(s.style.display=`none`);let l=kv(e.dataset.previewName||``),u=(c||``).split(`
|
|
1161
1161
|
`);i.textContent=r(`workspace.lineCount`,{count:u.length});let d=`<table class="workspace-preview-code-table"><tbody>`;for(let e=0;e<u.length;e++)d+=`<tr><td class="line-num">${e+1}</td><td class="line-content"><code class="${l}">${Z(u[e])}</code></td></tr>`;d+=`</tbody></table>`,t.innerHTML=d}}Y_(u)}function Y_(e){let t=document.getElementById(`workspacePreviewCopyBtn`);t&&(e?t.title=r(`workspace.copyAllTitle`)+`
|
|
1162
|
-
`+r(`workspace.copyMarkdownHint`):t.title=r(`workspace.copyAllTitle`))}async function X_(e){if(typeof mermaid>`u`)return;let t=e.querySelectorAll(`.mermaid`);for(let e of t){if(e.querySelector(`svg`))continue;let t=e.getAttribute(`data-raw-code`),n=t?decodeURIComponent(t):e.textContent||``;try{await mermaid.run({nodes:[e]}),typeof
|
|
1162
|
+
`+r(`workspace.copyMarkdownHint`):t.title=r(`workspace.copyAllTitle`))}async function X_(e){if(typeof mermaid>`u`)return;let t=e.querySelectorAll(`.mermaid`);for(let e of t){if(e.querySelector(`svg`))continue;let t=e.getAttribute(`data-raw-code`),n=t?decodeURIComponent(t):e.textContent||``;try{await mermaid.run({nodes:[e]}),typeof st==`function`&&st(e)}catch{e.textContent=n}}}function Z_(e){e.querySelectorAll(`.code-copy-btn`).forEach(e=>{e.dataset.bound||(e.dataset.bound=`true`,e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.closest(`.code-block-container`);if(n){let t=n.querySelector(`pre code`);t&&Ve(t.textContent||``,e)}}))}),e.dataset.ctrlClickBound||(e.dataset.ctrlClickBound=`true`,e.addEventListener(`click`,e=>{if(!e.ctrlKey&&!e.metaKey||e.button!==0)return;let t=e.target.closest(`code`);if(!t){let n=e.target.closest(`pre`);if(n&&(t=n.querySelector(`code`)),!t){let n=e.target.closest(`.code-block-container`);n&&(t=n.querySelector(`code`))}}if(!t||e.target.closest(`.code-copy-btn`))return;e.preventDefault();let n=t.textContent;n&&navigator.clipboard.writeText(n).then(()=>{P(r(`workspace.codeCopiedToClipboard`),`success`)}).catch(()=>{let e=document.createElement(`textarea`);e.value=n,e.style.position=`fixed`,e.style.left=`-999999px`,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),P(r(`workspace.codeCopiedToClipboard`),`success`)})}))}async function Q_(e=!1){let t=document.getElementById(`workspacePreviewArea`);if(!e&&t.dataset.editMode===`true`&&t.classList.contains(`has-unsaved`)&&!await rv(r(`workspace.actionClosePreview`)))return!1;nv(!1),Oh&&=(Oh.abort(),null);let n=document.getElementById(`workspacePanel`),i=document.getElementById(`workspacePreviewContent`);i.classList.remove(`xlsx-mode`),i.classList.remove(`markdown-rendered`),delete t.dataset.markdownText,delete t.dataset.htmlText,delete t.dataset.previewMode;let a=document.getElementById(`workspacePreviewMdToggleBtn`);if(a&&(a.classList.remove(`active`),a.style.display=`none`,W_(a,!1)),t.classList.contains(`fullscreen`)){t.classList.remove(`fullscreen`),n.classList.remove(`preview-fullscreen`);let e=document.getElementById(`workspacePreviewFullscreenBtn`);e&&(e.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>`,e.title=r(`workspace.fullscreenPreview`))}Nn();let o=document.getElementById(`workspacePreviewRail`);o&&o.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove()),Vg&&=(Vg.destroy(),null),Hg=1,Wg=1,C_&&=(URL.revokeObjectURL(C_),null);let s=document.getElementById(`workspacePreviewExportMenu`);s&&(s.style.display=`none`);let c=document.getElementById(`workspacePreviewCopyBtn`);return c&&(c.title=r(`workspace.copyAllTitle`)),t.style.display=`none`,document.getElementById(`workspacePreviewContent`).innerHTML=``,Dh&&(Dh=!1,Hv(!1)),!0}function $_(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePreviewContent`),n=document.getElementById(`workspacePreviewEditBtn`),i=document.getElementById(`workspacePreviewSaveBtn`),a=document.getElementById(`workspacePreviewCancelBtn`),o=document.getElementById(`workspacePreviewCopyBtn`),s=document.getElementById(`workspacePreviewDownloadBtn`),c=document.getElementById(`workspacePreviewMdToggleBtn`);document.getElementById(`workspacePreviewFullscreenBtn`);let l=document.getElementById(`workspacePreviewLineCount`),u=document.getElementById(`workspacePreviewFilename`),d=e.dataset.origContent||``;e.dataset.editMode=`true`,i.title=r(`workspace.saveChanges`),i.disabled=!1,o.style.display=`none`,s.style.display=`none`,c.style.display=`none`,n.style.display=`none`;let f=document.getElementById(`workspacePreviewExportMenu`);f&&(f.style.display=`none`),i.style.display=``,a.style.display=``,t.innerHTML=`<textarea class="workspace-preview-editor" id="workspacePreviewEditor" spellcheck="false"></textarea>`;let p=t.querySelector(`#workspacePreviewEditor`);p.value=d,p.focus(),p.setSelectionRange(p.value.length,p.value.length),l.textContent=r(`workspace.lineCount`,{count:d.split(`
|
|
1163
1163
|
`).length}),u.classList.add(`modified`),u.textContent=(e.dataset.previewName||``)+` *`,p.addEventListener(`input`,()=>{p.value===d?(e.classList.remove(`has-unsaved`),l.textContent=r(`workspace.lineCount`,{count:p.value.split(`
|
|
1164
1164
|
`).length})):(e.classList.add(`has-unsaved`),l.textContent=r(`workspace.linesModified`,{count:p.value.split(`
|
|
1165
|
-
`).length}))})}async function ev(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePreviewEditor`);if(!t)return;let n=e.dataset.previewPath,a=t.value;if(a===(e.dataset.origContent||``)){tv();return}let o=document.getElementById(`workspacePreviewSaveBtn`),s=o.title;o.title=r(`workspace.saving`),o.disabled=!0;try{let t=await Ct(n,a);if(t.success){i.info(`[WorkspacePanel] file save successful:`,n),
|
|
1165
|
+
`).length}))})}async function ev(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePreviewEditor`);if(!t)return;let n=e.dataset.previewPath,a=t.value;if(a===(e.dataset.origContent||``)){tv();return}let o=document.getElementById(`workspacePreviewSaveBtn`),s=o.title;o.title=r(`workspace.saving`),o.disabled=!0;try{let t=await Ct(n,a);if(t.success){i.info(`[WorkspacePanel] file save successful:`,n),P(r(`workspace.saveSuccess`)),e.dataset.origContent=a,nv(!1);let t=e.dataset.previewName;await Bg(n,t)}else i.error(`[WorkspacePanel] filesave failed:`,n,t.error),P(r(`workspace.saveFailedWithError`,{error:t.error||r(`workspace.unknownError`)})),o.title=s,o.disabled=!1}catch(e){i.error(`[WorkspacePanel] file saveexception:`,n,e),P(r(`workspace.saveFailedWithError`,{error:e.message||e})),o.title=s,o.disabled=!1}}async function tv(){let e=document.getElementById(`workspacePreviewArea`);if(e.classList.contains(`has-unsaved`)&&!await rv(r(`workspace.actionCancelEdit`)))return;nv(!0);let t=e.dataset.previewPath,n=e.dataset.previewName;t&&n&&await Bg(t,n)}function nv(e){let t=document.getElementById(`workspacePreviewArea`),n=document.getElementById(`workspacePreviewFilename`),r=document.getElementById(`workspacePreviewSaveBtn`),i=document.getElementById(`workspacePreviewCancelBtn`);delete t.dataset.editMode,t.classList.remove(`has-unsaved`),n.classList.remove(`modified`),r.style.display=`none`,i.style.display=`none`}async function rv(e){return typeof window.showCustomConfirm==`function`?await window.showCustomConfirm(r(`workspace.discardChangesPrompt`,{action:e}),r(`workspace.unsavedChanges`)):window.confirm(r(`workspace.discardChangesPrompt`,{action:e}))}function iv(e){let t=document.getElementById(`workspacePreviewArea`);if(t.style.display===`none`)return;if(t.dataset.editMode===`true`){(e.ctrlKey||e.metaKey)&&e.key===`s`&&(e.preventDefault(),ev()),e.key===`Escape`&&(e.preventDefault(),tv());return}let n=(e.target?.tagName||``).toLowerCase();if(n===`input`||n===`textarea`||e.target?.isContentEditable)return;let r=t.dataset.previewType;if(!(r!==`pdf`&&r!==`pptx`)){if(e.key===`ArrowLeft`){e.preventDefault();let t=document.getElementById(r===`pdf`?`pdfPrevPage`:`pptxPrevSlide`);t&&!t.disabled&&t.click()}else if(e.key===`ArrowRight`){e.preventDefault();let t=document.getElementById(r===`pdf`?`pdfNextPage`:`pptxNextSlide`);t&&!t.disabled&&t.click()}}}async function av(e,t){if(wh)return;wh=!0,uv(!0);let n=fv(e),i=new AbortController,a=[],o=()=>{if(a.length<2)return 0;let e=a[0],t=a[a.length-1],n=(t.time-e.time)/1e3;return n<=0?0:(t.loaded-e.loaded)/n},s=gv(()=>i.abort());s.classList.add(`download-mode`),_v(s,{percent:0,fileName:t,loaded:0,totalBytes:0,speed:0});try{let c=await Bt(e,({loaded:e,total:r,percent:i})=>{pv(n,i);let c=Date.now();a.push({time:c,loaded:e}),a.length>8&&a.shift(),_v(s,{percent:i,fileName:t,loaded:e,totalBytes:r,speed:o()})},i.signal);if(c.aborted){vv(s,r(`workspace.downloadCanceled`),!0),P(r(`workspace.downloadCanceled`),`info`);return}if(!c.success){vv(s,r(`workspace.downloadFailed`),!0),P(r(`workspace.downloadFailedWithError`,{error:c.error}),`error`);return}sv(c.blob,c.name||t),_v(s,{percent:100,fileName:t,loaded:c.blob.size,totalBytes:c.blob.size,speed:0,statusText:r(`workspace.savingToLocal`)}),setTimeout(()=>{vv(s,r(`workspace.savedToLocal`),!1)},1500),P(r(`workspace.downloaded`,{name:c.name||t}),`success`)}catch(e){e.name===`AbortError`?(vv(s,r(`workspace.downloadCanceled`),!0),P(r(`workspace.downloadCanceled`),`info`)):(vv(s,r(`workspace.downloadFailed`),!0),P(r(`workspace.downloadFailedWithError`,{error:e.message}),`error`))}finally{setTimeout(()=>mv(n),600),wh=!1,uv(!1)}}async function ov(){if(Y.size===0||wh)return;let e=Array.from(Y);if(e.length===1){let t=e[0].split(/[\\/]/).pop();await av(e[0],t);return}wh=!0,uv(!0);let t=new AbortController,n=[],i=()=>{if(n.length<2)return 0;let e=n[0],t=n[n.length-1],r=(t.time-e.time)/1e3;return r<=0?0:(t.loaded-e.loaded)/r},a=r(`workspace.fileCount`,{count:e.length}),o=gv(()=>t.abort());o.classList.add(`download-mode`),_v(o,{percent:0,fileName:a,loaded:0,totalBytes:0,speed:0});try{let s=await At(e,({loaded:e,total:t,percent:r})=>{let s=Date.now();n.push({time:s,loaded:e}),n.length>8&&n.shift(),_v(o,{percent:r,fileName:a,loaded:e,totalBytes:t,speed:i()})},t.signal);if(s.aborted){vv(o,r(`workspace.downloadCanceled`),!0),P(r(`workspace.downloadCanceled`),`info`);return}s.success&&s.blob?(sv(s.blob,s.name||`workspace.zip`),vv(o,r(`workspace.downloadedCount`,{count:e.length}),!1),P(r(`workspace.downloadedZip`,{count:e.length}),`success`)):(vv(o,r(`workspace.downloadFailed`),!0),P(r(`workspace.downloadFailedWithError`,{error:s.error||r(`workspace.unknownError`)}),`error`))}catch(e){e.name===`AbortError`?(vv(o,r(`workspace.downloadCanceled`),!0),P(r(`workspace.downloadCanceled`),`info`)):(vv(o,r(`workspace.downloadFailed`),!0),P(r(`workspace.downloadFailedWithError`,{error:e.message}),`error`))}finally{wh=!1,uv(!1)}}function sv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),6e4)}function cv(){let e=document.getElementById(`workspaceFileInput`);e&&e.click()}async function lv(e){let t=e.target.files;if(!t||t.length===0)return;let n=Array.from(t);e.target.value=``,await bv(n)}function uv(e){document.querySelectorAll(`.workspace-file-btn.download`).forEach(t=>{t.disabled=e});let t=document.getElementById(`workspaceDownloadDirBtn`);t&&(t.disabled=e||Y.size===0);let n=document.getElementById(`workspacePreviewDownloadBtn`);n&&(n.disabled=e)}var dv=new Map;function fv(e){return dv.set(e,0),hv(),e}function pv(e,t){if(!e)return;let n=e;dv.set(n,t);let r=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(e=>e.dataset.path===n);if(r){let e=r.querySelector(`.workspace-file-progress`);e||(e=document.createElement(`div`),e.className=`workspace-file-progress`,e.innerHTML=`<div class="workspace-file-progress-bar"></div>`,r.appendChild(e));let n=e.querySelector(`.workspace-file-progress-bar`);n&&(n.style.width=t+`%`)}}function mv(e){if(!e)return;let t=e;dv.delete(t);let n=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(e=>e.dataset.path===t);if(n){let e=n.querySelector(`.workspace-file-progress`);e&&e.remove()}}function hv(){for(let[e,t]of dv){let n=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.path===e);if(n&&!n.querySelector(`.workspace-file-progress`)){let e=document.createElement(`div`);e.className=`workspace-file-progress`,e.innerHTML=`<div class="workspace-file-progress-bar" style="width:${t}%"></div>`,n.appendChild(e)}}}function gv(e){let t=document.createElement(`div`);t.className=`workspace-upload-progress`,t.innerHTML=`
|
|
1166
1166
|
<div class="workspace-upload-progress-header">
|
|
1167
1167
|
<span class="workspace-upload-progress-title">${r(`workspace.uploading`)}</span>
|
|
1168
1168
|
<button class="workspace-upload-progress-cancel" title="${r(`workspace.cancelUpload`)}">
|
|
@@ -1179,8 +1179,8 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1179
1179
|
<span class="workspace-upload-progress-bytes"></span>
|
|
1180
1180
|
<span class="workspace-upload-progress-speed"></span>
|
|
1181
1181
|
</div>
|
|
1182
|
-
`,document.body.appendChild(t);let n=t.querySelector(`.workspace-upload-progress-cancel`);return n&&n.addEventListener(`click`,()=>{n.style.display=`none`,typeof e==`function`&&e()}),t}function _v(e,t){if(!e)return;let{percent:n,completed:i,total:a,fileName:o,loaded:s,totalBytes:c,speed:l,statusText:u}=t,d=e.querySelector(`.workspace-upload-progress-title`),f=e.querySelector(`.workspace-upload-progress-file`),p=e.querySelector(`.workspace-upload-progress-bar`),m=e.querySelector(`.workspace-upload-progress-bytes`),h=e.querySelector(`.workspace-upload-progress-speed`),g=e.classList.contains(`download-mode`)?r(`workspace.downloadInProgress`):r(`workspace.uploadInProgress`);d&&(u?d.textContent=u:i!=null&&a!=null?d.textContent=`${g} ${i}/${a} · ${n}%`:d.textContent=`${g} ${n}%`),f&&o&&(f.textContent=o,f.title=o),p&&(p.style.width=n+`%`),m&&(s!=null&&c!=null&&c>0?m.textContent=`${Lt(s)} / ${Lt(c)}`:s!=null&&(m.textContent=Lt(s))),h&&(h.textContent=l>0?`${Lt(l)}/s`:``)}function vv(e,t,n){if(!e)return;let r=e.querySelector(`.workspace-upload-progress-title`),i=e.querySelector(`.workspace-upload-progress-cancel`),a=e.querySelector(`.workspace-upload-progress-bar`);i&&(i.style.display=`none`),r&&(r.textContent=t),a&&!n&&(a.style.width=`100%`),e.classList.add(`workspace-upload-progress-done`),n&&e.classList.add(`workspace-upload-progress-error`),setTimeout(()=>{try{e.remove()}catch{}},1500)}function yv(e){let t=document.getElementById(`workspaceUploadBtn`);t&&(t.disabled=e,e?(t.dataset.originalHtml=t.innerHTML,t.innerHTML=`<span class="workspace-upload-spinner"></span>`):t.dataset.originalHtml&&(t.innerHTML=t.dataset.originalHtml,delete t.dataset.originalHtml));let n=document.getElementById(`workspacePanel`);n&&n.classList.toggle(`upload-in-progress`,e)}async function bv(e){let t=Array.from(e);if(t.length===0||Th)return;Th=!0,yv(!0);let n=await jt();if(!n){F(r(`workspace.agentNotConnectedUpload`),`error`),Th=!1,yv(!1);return}let i=new Set;try{let e=await kt(J);e.success&&Array.isArray(e.entries)&&(i=new Set(e.entries.map(e=>e.name)))}catch{}let a=0,o=0,s=0,c=t.reduce((e,t)=>e+t.size,0),l=Array(t.length).fill(0),u=new Set,d=!1,f=``,p=[],m=()=>{if(p.length<2)return 0;let e=p[0],t=p[p.length-1],n=(t.time-e.time)/1e3;return n<=0?0:(t.loaded-e.loaded)/n},h=gv(()=>{d=!0;for(let e of u)try{e.abort()}catch{}u.clear()}),g=e=>{e&&(f=e);let n=l.reduce((e,t)=>e+t,0),r=c>0?Math.round(n/c*100):0,i=Date.now();p.push({time:i,loaded:n}),p.length>8&&p.shift(),_v(h,{percent:r,completed:a+o+s,total:t.length,fileName:f,loaded:n,totalBytes:c,speed:m()})};g();for(let e=0;e<t.length&&!d;e+=3){let c=t.slice(e,e+3),f=await Promise.allSettled(c.map(async(t,a)=>{let o=e+a,s=Ph(t.name),c=sg(`${J}/${s}`);if(i.has(s))throw l[o]=t.size,g(s),Error(`__SKIPPED__`);if(d)throw Error(`__CANCELLED__`);await new Promise((e,i)=>{let a=new XMLHttpRequest;u.add(a);let s=`${n.url}/api/fs/upload-stream?path=${encodeURIComponent(c)}`;a.open(`POST`,s);for(let[e,t]of Object.entries(zt(n)))a.setRequestHeader(e,t);a.upload.onprogress=e=>{e.lengthComputable&&(l[o]=e.loaded,g(t.name))},a.onload=()=>{if(u.delete(a),d){i(Error(`__CANCELLED__`));return}if(a.status>=200&&a.status<300)try{let n=JSON.parse(a.responseText);n.success?(l[o]=t.size,g(t.name),e()):i(Error(n.error||r(`workspace.uploadFailed`)))}catch{i(Error(r(`workspace.parseResponseFailed`)))}else try{let e=JSON.parse(a.responseText);i(Error(e.error||r(`workspace.uploadFailedWithStatus`,{status:a.status})))}catch{i(Error(r(`workspace.uploadFailedWithStatus`,{status:a.status})))}},a.onerror=()=>{u.delete(a),i(Error(d?`__CANCELLED__`:r(`workspace.networkError`)))},a.onabort=()=>{u.delete(a),i(Error(`__CANCELLED__`))},a.send(t)})}));for(let e of f)if(e.status===`fulfilled`)a++;else{let t=e.reason&&e.reason.message?e.reason.message:``;t.includes(`__SKIPPED__`)||t.includes(`已存在`)?o++:t.includes(`__CANCELLED__`)||s++}}let _,v=!1;if(d)_=r(`workspace.uploadCanceled`),v=!0;else{let e=[];a>0&&e.push(r(`workspace.uploadSuccessCount`,{count:a})),o>0&&e.push(r(`workspace.uploadSkippedCount`,{count:o})),s>0&&e.push(r(`workspace.uploadFailedCount`,{count:s})),_=e.length>0?r(`workspace.uploadCompleteWithStats`,{stats:e.join(` / `)}):r(`workspace.uploadComplete`),v=s>0}vv(h,_,v),a>0&&F(r(`workspace.uploadedFiles`,{count:a}),`success`),o>0&&F(r(`workspace.filesSkipped`,{count:o}),`info`),s>0&&F(r(`workspace.filesUploadFailed`,{count:s}),`error`),d&&F(r(`workspace.uploadCanceled`),`info`),Th=!1,yv(!1),a>0&&(await Tv(),vy(t[t.length-1].name))}function xv(){let e=document.getElementById(`workspacePanel`);if(!e)return;let t=document.getElementById(`workspacePanelContent`);t.addEventListener(`dragstart`,e=>{let t=e.target.closest(`.workspace-file-item`);if(!t)return;let n=t.dataset.path,r=t.dataset.name;e.dataTransfer.setData(`application/x-workspace-move`,JSON.stringify({path:n,name:r})),e.dataTransfer.effectAllowed=`move`,t.classList.add(`dragging`);let i=()=>{t.classList.remove(`dragging`),t.removeEventListener(`dragend`,i)};t.addEventListener(`dragend`,i)}),t.addEventListener(`dragover`,n=>{n.preventDefault(),n.stopPropagation();let r=n.target.closest(`.workspace-file-item.directory`);t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),r?(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(`application/x-workspace-move`)?`move`:`copy`,r.classList.add(`drop-target`),e.classList.remove(`drag-over`)):n.dataTransfer.types.includes(`application/x-workspace-move`)||e.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,n=>{n.preventDefault(),n.stopPropagation(),t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`)}),t.addEventListener(`drop`,async n=>{n.preventDefault(),n.stopPropagation();let i=n.target.closest(`.workspace-file-item.directory`);if(t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`),i&&n.dataTransfer.types.includes(`application/x-workspace-move`)){try{let e=JSON.parse(n.dataTransfer.getData(`application/x-workspace-move`)),t=e.path,a=i.dataset.path,o=e.name,s=sg(t),c=sg(a);if(s===c)return;if(s.startsWith(c+`/`)){F(r(`workspace.cannotMoveToSubdir`),`error`);return}F(r(`workspace.moving`),`info`);let l=await Tt(t,a);if(l.success){F(r(`workspace.movedToDir`,{name:o}),`success`),cg(J),cg(a);let e=a.split(/[\\/]/).pop();await Tv(),vy(e)}else F(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){F(r(`workspace.moveFailed`,{error:e.message}),`error`)}return}if(i&&n.dataTransfer.files&&n.dataTransfer.files.length>0){let e=i.dataset.path;e.split(/[\\/]/).pop(),Nh(J),J=e,await bv(n.dataTransfer.files),Ev(),Dv();return}if(n.dataTransfer.files&&n.dataTransfer.files.length>0){await bv(n.dataTransfer.files);return}}),e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.add(`drag-over`)}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.remove(`drag-over`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),t.dataTransfer.types.includes(`application/x-workspace-move`))return;e.classList.remove(`drag-over`);let n=t.dataTransfer.files;!n||n.length===0||await bv(n)})}async function Sv(){try{let e=document.getElementById(`workspaceAgentName`);if(!e)return;let t=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=t.pairedAgents||[],r=t.activeAgentId;if(r){let t=n.find(e=>e.id===r);if(t&&t.name){e.textContent=` · ${t.name}`,e.style.display=``;return}}e.textContent=``,e.style.display=`none`}catch(e){i.debug(`[WorkspacePanel] update agentname failed:`,e)}}async function Cv(e,t){if(t===`local`&&!(!e.pairedAgents&&!e.activeAgentId)&&(await Sv(),e.activeAgentId?.newValue!==e.activeAgentId?.oldValue)){i.debug(`[WorkspacePanel] Agent changed,refreshworking directory`),xt(),ch=null,J=null,lh=[],Y.clear(),Uv=``,Wv=[],Gv=!1,tg.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await $h()}}async function wv(){if(lh.length===0)return;let e=lh.pop();Y.clear(),await eg(e)}async function Tv(e){if(!J){let e=ch||await Kt();if(!e){F(r(`workspace.refreshFailed`),`error`);return}ch=e,J=e}if(cg(J),Y.clear(),by(),Gv&&Uv?(Wv=await wt(J,Uv),gg()):await og(J),Q_(),Dg(),e!==void 0){let t=document.getElementById(`workspacePanelContent`);t&&requestAnimationFrame(()=>{t.scrollTop=e})}}function Ev(){let e=document.getElementById(`workspaceBreadcrumb`);if(!J){e.innerHTML=``;return}let t=sg(J).split(`/`).filter(Boolean),n=ch?sg(ch).replace(/\/$/,``):null,i=``,a=``;for(let e=0;e<t.length;e++){a=e===0?/^[a-zA-Z]:$/.test(t[e])?t[e]+`/`:`/`+t[e]:(a.endsWith(`/`)?a:a+`/`)+t[e];let r=e===t.length-1,o=!n||a===n||a.startsWith(n+`/`);e>0&&(i+=`<span class="workspace-breadcrumb-sep">/</span>`),r?i+=`<span class="workspace-breadcrumb-current">${Z(t[e])}</span>`:o?i+=`<span class="workspace-breadcrumb-link" data-path="${Z(a)}">${Z(t[e])}</span>`:i+=`<span class="workspace-breadcrumb-disabled">${Z(t[e])}</span>`}e.innerHTML=i||`<span class="workspace-breadcrumb-current">/</span>`,e.querySelectorAll(`.workspace-breadcrumb-link`).forEach(e=>{e.addEventListener(`click`,async t=>{t.stopPropagation();let n=e.dataset.path,r=lh.findIndex(e=>e===n);lh=r>=0?lh.slice(0,r):[],Y.clear(),await eg(n)}),e.addEventListener(`dragover`,t=>{t.dataTransfer.types.includes(`application/x-workspace-move`)&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`,e.classList.add(`drop-target`))}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`),t.dataTransfer.types.includes(`application/x-workspace-move`))try{let n=JSON.parse(t.dataTransfer.getData(`application/x-workspace-move`)),i=n.path,a=e.dataset.path,o=n.name,s=sg(i),c=sg(a);if(s===c)return;if(c.startsWith(s+`/`)){F(r(`workspace.cannotMoveToSubdir`),`error`);return}F(r(`workspace.moving`),`info`);let l=await Tt(i,a);l.success?(F(r(`workspace.movedToTarget`,{name:o,target:a.split(/[\\/]/).pop()}),`success`),cg(J),cg(a),await Tv()):F(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){F(r(`workspace.moveFailed`,{error:e.message}),`error`)}})})}function Dv(){let e=document.getElementById(`workspaceBackBtn`);e.disabled=!(ch&&J&&J!==ch)}function Ov(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-error">${Z(e)}</div>`}function Z(e){return e?String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`):``}function kv(e){let t=(e.split(`.`).pop()||``).toLowerCase(),n={js:`javascript`,mjs:`javascript`,ts:`typescript`,jsx:`jsx`,tsx:`tsx`,html:`html`,htm:`html`,css:`css`,scss:`scss`,less:`less`,json:`json`,xml:`xml`,yaml:`yaml`,yml:`yaml`,py:`python`,java:`java`,c:`c`,cpp:`cpp`,h:`c`,go:`go`,rs:`rust`,rb:`ruby`,php:`php`,sql:`sql`,sh:`bash`,bash:`bash`,zsh:`bash`,md:`markdown`,vue:`html`,svelte:`html`};return n[t]?`language-${n[t]}`:``}async function Av(){J&&await og(J)}async function jv(){xt(),ch=null,J=null,lh=[],Y.clear(),Uv=``,Wv=[],Gv=!1,tg.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await $h()}function Mv(e){let t=document.getElementById(`workspacePanelContainer`);if(t)if(e){t.style.display=``;let e=document.getElementById(`workspacePanel`),n=!!(e&&e.classList.contains(`expanded`));vh&&e&&!n?Xh().catch(e=>i.warn(`[WorkspacePanel] reopen panel after reconnect failed`,e)):n&&!J&&$h().catch(e=>i.warn(`[WorkspacePanel] navigate after reconnect failed`,e)),bh&&Jh()}else t.style.display=`none`,Hv(!0)}function Nv(e,t){let n=t.toLowerCase(),r=e.toLowerCase();return r===n?``:r.startsWith(n+`/`)?e.substring(t.length+1):null}function Pv(e,t){let n=t.split(`/`).filter(Boolean).pop();if(!n)return null;let r=e.lastIndexOf(`/`+n);if(r===-1)return null;let i=e.substring(r+n.length+1);return i===``?``:i}function Fv(e,t){if(!e)return null;let n=sg(t);if(!n)return null;let r=sg(e).trim();if(!r||r===`.`||r===`~`||r.startsWith(`~/`))return null;if(!(r.startsWith(`/`)||/^[a-zA-Z]:\//.test(r)))return n+`/`+r;let i=Nv(r,n);return i===null&&(i=Pv(r,n)),i===null?null:i===``?n:n+`/`+i}async function Iv(e){if(!(e===`~`||e&&e.startsWith(`~/`)))return e;try{let t=await Pt();if(t)return sg(e===`~`?t:t+`/`+e.slice(2))}catch{}return e}async function Lv(e){if(!e)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);if(!t||!n)return;if(t.classList.add(`expanded`),Be(t),n.classList.add(`click-opened`),ch||=await Kt(),!ch){Ov(r(`workspace.noWorkspace`));return}let i=Fv(await Iv(e),ch);if(!i){Ov(r(`artifacts.locateFailed`));return}let a=i.lastIndexOf(`/`),o=a>0?i.substring(0,a):ch,s=a>0?i.substring(a+1):i;cg(o),await eg(o);let c=e=>{let t=()=>{let t=null;return document.querySelectorAll(`.workspace-file-item`).forEach(n=>{n.dataset.name===e&&(t=n)}),t},n=t();if(n||!fg)return n;let r=fg.sorted.findIndex(t=>t.name===e);if(r<0)return null;let i=document.getElementById(`workspacePanelContent`);if(!i)return null;let{itemHeight:a}=fg;return i.scrollTop=Math.max(0,r*a-i.clientHeight/2+a/2),hg(),t()};setTimeout(async()=>{let e=c(s);e||=(cg(o),await eg(o),await new Promise(e=>setTimeout(e,300)),c(s)),e?(e.classList.add(`highlighted`),e.scrollIntoView({behavior:`smooth`,block:`center`}),setTimeout(()=>e.classList.remove(`highlighted`),3e3)):F(r(`artifacts.fileNotFound`))},300)}async function Rv(e,t){if(!e)return;let n=document.getElementById(`workspacePanel`),i=document.getElementById(`workspacePanelContainer`);if(!n||!i)return;let a=n.classList.contains(`expanded`);if(n.classList.add(`expanded`),Be(n),i.classList.add(`click-opened`),ch||=await Kt(),!ch){Ov(r(`workspace.noWorkspace`));return}let o=Fv(await Iv(e),ch);if(!o){Ov(r(`artifacts.locateFailed`));return}await Q_(!0),await Bg(o,t),Dh=!a}async function zv(){await Q_(!0)}function Bv(){Hv(!0)}async function Vv(e){return!e||(ch||=await Kt(),!ch)?null:Fv(await Iv(e),ch)}async function Hv(e=!1){if(e&&await Q_(!0)===!1)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);t&&(t.classList.remove(`expanded`),Re(t),e||chrome.storage.local.set({[_h]:!1}).catch(()=>{})),n&&(n.classList.remove(`hover-expanded`),n.classList.remove(`click-opened`),vh&&!e&&(vh=!1,bh=!1,n.classList.add(`closing-no-anim`),Hh(),requestAnimationFrame(()=>n.classList.remove(`closing-no-anim`))))}var Uv=``,Wv=[],Gv=!1,Kv=[],qv=-1;function Jv(){try{chrome.storage.local.get([`workspaceSearchHistory`],e=>{Kv=e.workspaceSearchHistory||[]})}catch{}}function Yv(e){if(!e.trim())return;let t=Kv.indexOf(e);t!==-1&&Kv.splice(t,1),Kv.push(e),Kv.length>20&&Kv.shift();try{chrome.storage.local.set({workspaceSearchHistory:Kv})}catch{}}function Xv(e){Uv=e.target.value.trim();let t=document.getElementById(`workspaceSearchClear`);t.style.display=Uv?``:`none`}async function Zv(){if(!Uv){Gv=!1,Wv=[],gg(),Dg();return}Yv(Uv),qv=-1,F(r(`workspace.searching`),`info`),Wv=await wt(J,Uv),Gv=!0,gg(),Dg()}async function Qv(){let e=document.getElementById(`workspaceSearchInput`),t=document.getElementById(`workspaceToolbar`),n=t.querySelector(`.workspace-search-box`);e.value=``,Uv=``,Gv=!1,Wv=[],Y.clear(),document.getElementById(`workspaceSearchClear`).style.display=`none`,t.classList.remove(`search-focused`),n.classList.remove(`search-box-expanded`),e.blur(),await og(J),Dg(),by()}async function $v(e,t,n){let i=n===`directory`,a=r(i?`workspace.confirmDeleteDir`:`workspace.confirmDeleteFile`,{name:t,path:e});if(typeof window.showCustomConfirm!=`function`){if(!confirm(a))return}else if(!await window.showCustomConfirm(a,r(`workspace.confirmDeleteTitle`)))return;let o=document.getElementById(`workspacePanelContent`),s=o?o.scrollTop:0;try{let t=await jt();if(!t){F(r(`workspace.agentNotConnected`),`error`);return}let n=await(await fetch(`${t.url}/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(t)},body:JSON.stringify({path:e})})).json();n.success?(F(r(i?`workspace.dirDeleted`:`workspace.fileDeleted`),`success`),Y.delete(e),by(),await Tv(s)):F(r(`workspace.deleteFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}catch(e){F(r(`workspace.deleteFailedWithError`,{error:e.message}),`error`)}}async function ey(){if(Y.size===0)return;let e=Array.from(Y),t=e.map(e=>{let t=Mh.find(t=>t.path===e)||Wv.find(t=>t.fullPath===e);return t?t.name:e.split(/[\\/]/).pop()}),n=t.slice(0,5).map(e=>`• ${e}`).join(`
|
|
1183
|
-
`)+(t.length>5?r(`workspace.batchNamesMore`,{count:t.length}):``),i=r(`workspace.confirmBatchDelete`,{count:e.length,names:n});if(typeof window.showCustomConfirm!=`function`){if(!confirm(i))return}else if(!await window.showCustomConfirm(i,r(`workspace.confirmBatchDeleteTitle`)))return;let a=document.getElementById(`workspacePanelContent`),o=a?a.scrollTop:0;try{let t=await jt();if(!t){
|
|
1182
|
+
`,document.body.appendChild(t);let n=t.querySelector(`.workspace-upload-progress-cancel`);return n&&n.addEventListener(`click`,()=>{n.style.display=`none`,typeof e==`function`&&e()}),t}function _v(e,t){if(!e)return;let{percent:n,completed:i,total:a,fileName:o,loaded:s,totalBytes:c,speed:l,statusText:u}=t,d=e.querySelector(`.workspace-upload-progress-title`),f=e.querySelector(`.workspace-upload-progress-file`),p=e.querySelector(`.workspace-upload-progress-bar`),m=e.querySelector(`.workspace-upload-progress-bytes`),h=e.querySelector(`.workspace-upload-progress-speed`),g=e.classList.contains(`download-mode`)?r(`workspace.downloadInProgress`):r(`workspace.uploadInProgress`);d&&(u?d.textContent=u:i!=null&&a!=null?d.textContent=`${g} ${i}/${a} · ${n}%`:d.textContent=`${g} ${n}%`),f&&o&&(f.textContent=o,f.title=o),p&&(p.style.width=n+`%`),m&&(s!=null&&c!=null&&c>0?m.textContent=`${Lt(s)} / ${Lt(c)}`:s!=null&&(m.textContent=Lt(s))),h&&(h.textContent=l>0?`${Lt(l)}/s`:``)}function vv(e,t,n){if(!e)return;let r=e.querySelector(`.workspace-upload-progress-title`),i=e.querySelector(`.workspace-upload-progress-cancel`),a=e.querySelector(`.workspace-upload-progress-bar`);i&&(i.style.display=`none`),r&&(r.textContent=t),a&&!n&&(a.style.width=`100%`),e.classList.add(`workspace-upload-progress-done`),n&&e.classList.add(`workspace-upload-progress-error`),setTimeout(()=>{try{e.remove()}catch{}},1500)}function yv(e){let t=document.getElementById(`workspaceUploadBtn`);t&&(t.disabled=e,e?(t.dataset.originalHtml=t.innerHTML,t.innerHTML=`<span class="workspace-upload-spinner"></span>`):t.dataset.originalHtml&&(t.innerHTML=t.dataset.originalHtml,delete t.dataset.originalHtml));let n=document.getElementById(`workspacePanel`);n&&n.classList.toggle(`upload-in-progress`,e)}async function bv(e){let t=Array.from(e);if(t.length===0||Th)return;Th=!0,yv(!0);let n=await jt();if(!n){P(r(`workspace.agentNotConnectedUpload`),`error`),Th=!1,yv(!1);return}let i=new Set;try{let e=await kt(J);e.success&&Array.isArray(e.entries)&&(i=new Set(e.entries.map(e=>e.name)))}catch{}let a=0,o=0,s=0,c=t.reduce((e,t)=>e+t.size,0),l=Array(t.length).fill(0),u=new Set,d=!1,f=``,p=[],m=()=>{if(p.length<2)return 0;let e=p[0],t=p[p.length-1],n=(t.time-e.time)/1e3;return n<=0?0:(t.loaded-e.loaded)/n},h=gv(()=>{d=!0;for(let e of u)try{e.abort()}catch{}u.clear()}),g=e=>{e&&(f=e);let n=l.reduce((e,t)=>e+t,0),r=c>0?Math.round(n/c*100):0,i=Date.now();p.push({time:i,loaded:n}),p.length>8&&p.shift(),_v(h,{percent:r,completed:a+o+s,total:t.length,fileName:f,loaded:n,totalBytes:c,speed:m()})};g();for(let e=0;e<t.length&&!d;e+=3){let c=t.slice(e,e+3),f=await Promise.allSettled(c.map(async(t,a)=>{let o=e+a,s=Ph(t.name),c=sg(`${J}/${s}`);if(i.has(s))throw l[o]=t.size,g(s),Error(`__SKIPPED__`);if(d)throw Error(`__CANCELLED__`);await new Promise((e,i)=>{let a=new XMLHttpRequest;u.add(a);let s=`${n.url}/api/fs/upload-stream?path=${encodeURIComponent(c)}`;a.open(`POST`,s);for(let[e,t]of Object.entries(zt(n)))a.setRequestHeader(e,t);a.upload.onprogress=e=>{e.lengthComputable&&(l[o]=e.loaded,g(t.name))},a.onload=()=>{if(u.delete(a),d){i(Error(`__CANCELLED__`));return}if(a.status>=200&&a.status<300)try{let n=JSON.parse(a.responseText);n.success?(l[o]=t.size,g(t.name),e()):i(Error(n.error||r(`workspace.uploadFailed`)))}catch{i(Error(r(`workspace.parseResponseFailed`)))}else try{let e=JSON.parse(a.responseText);i(Error(e.error||r(`workspace.uploadFailedWithStatus`,{status:a.status})))}catch{i(Error(r(`workspace.uploadFailedWithStatus`,{status:a.status})))}},a.onerror=()=>{u.delete(a),i(Error(d?`__CANCELLED__`:r(`workspace.networkError`)))},a.onabort=()=>{u.delete(a),i(Error(`__CANCELLED__`))},a.send(t)})}));for(let e of f)if(e.status===`fulfilled`)a++;else{let t=e.reason&&e.reason.message?e.reason.message:``;t.includes(`__SKIPPED__`)||t.includes(`已存在`)?o++:t.includes(`__CANCELLED__`)||s++}}let _,v=!1;if(d)_=r(`workspace.uploadCanceled`),v=!0;else{let e=[];a>0&&e.push(r(`workspace.uploadSuccessCount`,{count:a})),o>0&&e.push(r(`workspace.uploadSkippedCount`,{count:o})),s>0&&e.push(r(`workspace.uploadFailedCount`,{count:s})),_=e.length>0?r(`workspace.uploadCompleteWithStats`,{stats:e.join(` / `)}):r(`workspace.uploadComplete`),v=s>0}vv(h,_,v),a>0&&P(r(`workspace.uploadedFiles`,{count:a}),`success`),o>0&&P(r(`workspace.filesSkipped`,{count:o}),`info`),s>0&&P(r(`workspace.filesUploadFailed`,{count:s}),`error`),d&&P(r(`workspace.uploadCanceled`),`info`),Th=!1,yv(!1),a>0&&(await Tv(),vy(t[t.length-1].name))}function xv(){let e=document.getElementById(`workspacePanel`);if(!e)return;let t=document.getElementById(`workspacePanelContent`);t.addEventListener(`dragstart`,e=>{let t=e.target.closest(`.workspace-file-item`);if(!t)return;let n=t.dataset.path,r=t.dataset.name;e.dataTransfer.setData(`application/x-workspace-move`,JSON.stringify({path:n,name:r})),e.dataTransfer.effectAllowed=`move`,t.classList.add(`dragging`);let i=()=>{t.classList.remove(`dragging`),t.removeEventListener(`dragend`,i)};t.addEventListener(`dragend`,i)}),t.addEventListener(`dragover`,n=>{n.preventDefault(),n.stopPropagation();let r=n.target.closest(`.workspace-file-item.directory`);t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),r?(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(`application/x-workspace-move`)?`move`:`copy`,r.classList.add(`drop-target`),e.classList.remove(`drag-over`)):n.dataTransfer.types.includes(`application/x-workspace-move`)||e.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,n=>{n.preventDefault(),n.stopPropagation(),t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`)}),t.addEventListener(`drop`,async n=>{n.preventDefault(),n.stopPropagation();let i=n.target.closest(`.workspace-file-item.directory`);if(t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`),i&&n.dataTransfer.types.includes(`application/x-workspace-move`)){try{let e=JSON.parse(n.dataTransfer.getData(`application/x-workspace-move`)),t=e.path,a=i.dataset.path,o=e.name,s=sg(t),c=sg(a);if(s===c)return;if(s.startsWith(c+`/`)){P(r(`workspace.cannotMoveToSubdir`),`error`);return}P(r(`workspace.moving`),`info`);let l=await Tt(t,a);if(l.success){P(r(`workspace.movedToDir`,{name:o}),`success`),cg(J),cg(a);let e=a.split(/[\\/]/).pop();await Tv(),vy(e)}else P(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){P(r(`workspace.moveFailed`,{error:e.message}),`error`)}return}if(i&&n.dataTransfer.files&&n.dataTransfer.files.length>0){let e=i.dataset.path;e.split(/[\\/]/).pop(),Nh(J),J=e,await bv(n.dataTransfer.files),Ev(),Dv();return}if(n.dataTransfer.files&&n.dataTransfer.files.length>0){await bv(n.dataTransfer.files);return}}),e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.add(`drag-over`)}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.remove(`drag-over`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),t.dataTransfer.types.includes(`application/x-workspace-move`))return;e.classList.remove(`drag-over`);let n=t.dataTransfer.files;!n||n.length===0||await bv(n)})}async function Sv(){try{let e=document.getElementById(`workspaceAgentName`);if(!e)return;let t=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=t.pairedAgents||[],r=t.activeAgentId;if(r){let t=n.find(e=>e.id===r);if(t&&t.name){e.textContent=` · ${t.name}`,e.style.display=``;return}}e.textContent=``,e.style.display=`none`}catch(e){i.debug(`[WorkspacePanel] update agentname failed:`,e)}}async function Cv(e,t){if(t===`local`&&!(!e.pairedAgents&&!e.activeAgentId)&&(await Sv(),e.activeAgentId?.newValue!==e.activeAgentId?.oldValue)){i.debug(`[WorkspacePanel] Agent changed,refreshworking directory`),xt(),ch=null,J=null,lh=[],Y.clear(),Uv=``,Wv=[],Gv=!1,tg.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await $h()}}async function wv(){if(lh.length===0)return;let e=lh.pop();Y.clear(),await eg(e)}async function Tv(e){if(!J){let e=ch||await Kt();if(!e){P(r(`workspace.refreshFailed`),`error`);return}ch=e,J=e}if(cg(J),Y.clear(),by(),Gv&&Uv?(Wv=await wt(J,Uv),gg()):await og(J),Q_(),Dg(),e!==void 0){let t=document.getElementById(`workspacePanelContent`);t&&requestAnimationFrame(()=>{t.scrollTop=e})}}function Ev(){let e=document.getElementById(`workspaceBreadcrumb`);if(!J){e.innerHTML=``;return}let t=sg(J).split(`/`).filter(Boolean),n=ch?sg(ch).replace(/\/$/,``):null,i=``,a=``;for(let e=0;e<t.length;e++){a=e===0?/^[a-zA-Z]:$/.test(t[e])?t[e]+`/`:`/`+t[e]:(a.endsWith(`/`)?a:a+`/`)+t[e];let r=e===t.length-1,o=!n||a===n||a.startsWith(n+`/`);e>0&&(i+=`<span class="workspace-breadcrumb-sep">/</span>`),r?i+=`<span class="workspace-breadcrumb-current">${Z(t[e])}</span>`:o?i+=`<span class="workspace-breadcrumb-link" data-path="${Z(a)}">${Z(t[e])}</span>`:i+=`<span class="workspace-breadcrumb-disabled">${Z(t[e])}</span>`}e.innerHTML=i||`<span class="workspace-breadcrumb-current">/</span>`,e.querySelectorAll(`.workspace-breadcrumb-link`).forEach(e=>{e.addEventListener(`click`,async t=>{t.stopPropagation();let n=e.dataset.path,r=lh.findIndex(e=>e===n);lh=r>=0?lh.slice(0,r):[],Y.clear(),await eg(n)}),e.addEventListener(`dragover`,t=>{t.dataTransfer.types.includes(`application/x-workspace-move`)&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`,e.classList.add(`drop-target`))}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`),t.dataTransfer.types.includes(`application/x-workspace-move`))try{let n=JSON.parse(t.dataTransfer.getData(`application/x-workspace-move`)),i=n.path,a=e.dataset.path,o=n.name,s=sg(i),c=sg(a);if(s===c)return;if(c.startsWith(s+`/`)){P(r(`workspace.cannotMoveToSubdir`),`error`);return}P(r(`workspace.moving`),`info`);let l=await Tt(i,a);l.success?(P(r(`workspace.movedToTarget`,{name:o,target:a.split(/[\\/]/).pop()}),`success`),cg(J),cg(a),await Tv()):P(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){P(r(`workspace.moveFailed`,{error:e.message}),`error`)}})})}function Dv(){let e=document.getElementById(`workspaceBackBtn`);e.disabled=!(ch&&J&&J!==ch)}function Ov(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-error">${Z(e)}</div>`}function Z(e){return e?String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`):``}function kv(e){let t=(e.split(`.`).pop()||``).toLowerCase(),n={js:`javascript`,mjs:`javascript`,ts:`typescript`,jsx:`jsx`,tsx:`tsx`,html:`html`,htm:`html`,css:`css`,scss:`scss`,less:`less`,json:`json`,xml:`xml`,yaml:`yaml`,yml:`yaml`,py:`python`,java:`java`,c:`c`,cpp:`cpp`,h:`c`,go:`go`,rs:`rust`,rb:`ruby`,php:`php`,sql:`sql`,sh:`bash`,bash:`bash`,zsh:`bash`,md:`markdown`,vue:`html`,svelte:`html`};return n[t]?`language-${n[t]}`:``}async function Av(){J&&await og(J)}async function jv(){xt(),ch=null,J=null,lh=[],Y.clear(),Uv=``,Wv=[],Gv=!1,tg.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await $h()}function Mv(e){let t=document.getElementById(`workspacePanelContainer`);if(t)if(e){t.style.display=``;let e=document.getElementById(`workspacePanel`),n=!!(e&&e.classList.contains(`expanded`));vh&&e&&!n?Xh().catch(e=>i.warn(`[WorkspacePanel] reopen panel after reconnect failed`,e)):n&&!J&&$h().catch(e=>i.warn(`[WorkspacePanel] navigate after reconnect failed`,e)),bh&&Jh()}else t.style.display=`none`,Hv(!0)}function Nv(e,t){let n=t.toLowerCase(),r=e.toLowerCase();return r===n?``:r.startsWith(n+`/`)?e.substring(t.length+1):null}function Pv(e,t){let n=t.split(`/`).filter(Boolean).pop();if(!n)return null;let r=e.lastIndexOf(`/`+n);if(r===-1)return null;let i=e.substring(r+n.length+1);return i===``?``:i}function Fv(e,t){if(!e)return null;let n=sg(t);if(!n)return null;let r=sg(e).trim();if(!r||r===`.`||r===`~`||r.startsWith(`~/`))return null;if(!(r.startsWith(`/`)||/^[a-zA-Z]:\//.test(r)))return n+`/`+r;let i=Nv(r,n);return i===null&&(i=Pv(r,n)),i===null?null:i===``?n:n+`/`+i}async function Iv(e){if(!(e===`~`||e&&e.startsWith(`~/`)))return e;try{let t=await Pt();if(t)return sg(e===`~`?t:t+`/`+e.slice(2))}catch{}return e}async function Lv(e){if(!e)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);if(!t||!n)return;if(t.classList.add(`expanded`),Fe(t),n.classList.add(`click-opened`),ch||=await Kt(),!ch){Ov(r(`workspace.noWorkspace`));return}let i=Fv(await Iv(e),ch);if(!i){Ov(r(`artifacts.locateFailed`));return}let a=i.lastIndexOf(`/`),o=a>0?i.substring(0,a):ch,s=a>0?i.substring(a+1):i;cg(o),await eg(o);let c=e=>{let t=()=>{let t=null;return document.querySelectorAll(`.workspace-file-item`).forEach(n=>{n.dataset.name===e&&(t=n)}),t},n=t();if(n||!fg)return n;let r=fg.sorted.findIndex(t=>t.name===e);if(r<0)return null;let i=document.getElementById(`workspacePanelContent`);if(!i)return null;let{itemHeight:a}=fg;return i.scrollTop=Math.max(0,r*a-i.clientHeight/2+a/2),hg(),t()};setTimeout(async()=>{let e=c(s);e||=(cg(o),await eg(o),await new Promise(e=>setTimeout(e,300)),c(s)),e?(e.classList.add(`highlighted`),e.scrollIntoView({behavior:`smooth`,block:`center`}),setTimeout(()=>e.classList.remove(`highlighted`),3e3)):P(r(`artifacts.fileNotFound`))},300)}async function Rv(e,t){if(!e)return;let n=document.getElementById(`workspacePanel`),i=document.getElementById(`workspacePanelContainer`);if(!n||!i)return;let a=n.classList.contains(`expanded`);if(n.classList.add(`expanded`),Fe(n),i.classList.add(`click-opened`),ch||=await Kt(),!ch){Ov(r(`workspace.noWorkspace`));return}let o=Fv(await Iv(e),ch);if(!o){Ov(r(`artifacts.locateFailed`));return}await Q_(!0),await Bg(o,t),Dh=!a}async function zv(){await Q_(!0)}function Bv(){Hv(!0)}async function Vv(e){return!e||(ch||=await Kt(),!ch)?null:Fv(await Iv(e),ch)}async function Hv(e=!1){if(e&&await Q_(!0)===!1)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);t&&(t.classList.remove(`expanded`),Le(t),e||chrome.storage.local.set({[_h]:!1}).catch(()=>{})),n&&(n.classList.remove(`hover-expanded`),n.classList.remove(`click-opened`),vh&&!e&&(vh=!1,bh=!1,n.classList.add(`closing-no-anim`),Hh(),requestAnimationFrame(()=>n.classList.remove(`closing-no-anim`))))}var Uv=``,Wv=[],Gv=!1,Kv=[],qv=-1;function Jv(){try{chrome.storage.local.get([`workspaceSearchHistory`],e=>{Kv=e.workspaceSearchHistory||[]})}catch{}}function Yv(e){if(!e.trim())return;let t=Kv.indexOf(e);t!==-1&&Kv.splice(t,1),Kv.push(e),Kv.length>20&&Kv.shift();try{chrome.storage.local.set({workspaceSearchHistory:Kv})}catch{}}function Xv(e){Uv=e.target.value.trim();let t=document.getElementById(`workspaceSearchClear`);t.style.display=Uv?``:`none`}async function Zv(){if(!Uv){Gv=!1,Wv=[],gg(),Dg();return}Yv(Uv),qv=-1,P(r(`workspace.searching`),`info`),Wv=await wt(J,Uv),Gv=!0,gg(),Dg()}async function Qv(){let e=document.getElementById(`workspaceSearchInput`),t=document.getElementById(`workspaceToolbar`),n=t.querySelector(`.workspace-search-box`);e.value=``,Uv=``,Gv=!1,Wv=[],Y.clear(),document.getElementById(`workspaceSearchClear`).style.display=`none`,t.classList.remove(`search-focused`),n.classList.remove(`search-box-expanded`),e.blur(),await og(J),Dg(),by()}async function $v(e,t,n){let i=n===`directory`,a=r(i?`workspace.confirmDeleteDir`:`workspace.confirmDeleteFile`,{name:t,path:e});if(typeof window.showCustomConfirm!=`function`){if(!confirm(a))return}else if(!await window.showCustomConfirm(a,r(`workspace.confirmDeleteTitle`)))return;let o=document.getElementById(`workspacePanelContent`),s=o?o.scrollTop:0;try{let t=await jt();if(!t){P(r(`workspace.agentNotConnected`),`error`);return}let n=await(await fetch(`${t.url}/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(t)},body:JSON.stringify({path:e})})).json();n.success?(P(r(i?`workspace.dirDeleted`:`workspace.fileDeleted`),`success`),Y.delete(e),by(),await Tv(s)):P(r(`workspace.deleteFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}catch(e){P(r(`workspace.deleteFailedWithError`,{error:e.message}),`error`)}}async function ey(){if(Y.size===0)return;let e=Array.from(Y),t=e.map(e=>{let t=Mh.find(t=>t.path===e)||Wv.find(t=>t.fullPath===e);return t?t.name:e.split(/[\\/]/).pop()}),n=t.slice(0,5).map(e=>`• ${e}`).join(`
|
|
1183
|
+
`)+(t.length>5?r(`workspace.batchNamesMore`,{count:t.length}):``),i=r(`workspace.confirmBatchDelete`,{count:e.length,names:n});if(typeof window.showCustomConfirm!=`function`){if(!confirm(i))return}else if(!await window.showCustomConfirm(i,r(`workspace.confirmBatchDeleteTitle`)))return;let a=document.getElementById(`workspacePanelContent`),o=a?a.scrollTop:0;try{let t=await jt();if(!t){P(r(`workspace.agentNotConnected`),`error`);return}let n=0,i=0;for(let r of e)try{(await(await fetch(`${t.url}/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(t)},body:JSON.stringify({path:r})})).json()).success?(Y.delete(r),n++):i++}catch{i++}n>0?(P(r(`workspace.deletedCount`,{success:n,failed:i>0?r(`workspace.deletedCountFailed`,{count:i}):``}),i>0?`warning`:`success`),by(),await Tv(o)):P(r(`workspace.deleteFailed`),`error`)}catch(e){P(r(`workspace.deleteFailedWithError`,{error:e.message}),`error`)}}function ty(e,t){let n=[{bit:256,ch:`r`},{bit:128,ch:`w`},{bit:64,ch:`x`},{bit:32,ch:`r`},{bit:16,ch:`w`},{bit:8,ch:`x`},{bit:4,ch:`r`},{bit:2,ch:`w`},{bit:1,ch:`x`}],r=t?`d`:`-`;for(let t of n)r+=e&t.bit?t.ch:`-`,t.ch===`x`&&e&t.bit<<9&&(r=r.slice(0,-1)+(t.ch===`x`?`s`:`S`));let i=(e&511).toString(8).padStart(3,`0`);return`${r} (${i})`}async function ny(e,t,n){let i=document.createElement(`div`);i.className=`modal-overlay show`,i.innerHTML=`
|
|
1184
1184
|
<div class="modal-container file-info-modal">
|
|
1185
1185
|
<button class="file-info-close" title="${r(`workspace.close`)}" style="position:absolute;top:10px;right:12px;background:none;border:none;font-size:20px;color:var(--text-tertiary);cursor:pointer;padding:4px 8px;line-height:1;transition:color 0.15s ease;">×</button>
|
|
1186
1186
|
<div class="modal-title">${Z(t)} - ${r(`workspace.fileDetailsLabel`)}</div>
|
|
@@ -1188,7 +1188,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1188
1188
|
<div class="modal-actions" style="display:flex;justify-content:flex-end;gap:8px;margin-top:12px;">
|
|
1189
1189
|
<button class="modal-btn-cancel" style="padding:6px 16px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);cursor:pointer;">${r(`workspace.close`)}</button>
|
|
1190
1190
|
</div>
|
|
1191
|
-
</div>`,document.body.appendChild(i);let o=()=>i.remove();i.querySelector(`.modal-btn-cancel`).addEventListener(`click`,o),i.querySelector(`.file-info-close`).addEventListener(`click`,o);try{let t=await Rt(e),n=i.querySelector(`.file-info-loading`);if(!t.success||!t.info){n.className=``,n.innerHTML=`<div class="workspace-panel-error">${r(`workspace.getDetailsFailed`,{error:t.error||r(`workspace.unknownError`)})}</div>`;return}let o=t.info,s=e=>e?new Date(e).toLocaleString(a()===`en`?`en-US`:`zh-CN`):`—`,c=o.isDirectory?r(`workspace.getTypeDir`):o.isSymbolicLink?r(`workspace.getTypeSymlink`):r(`workspace.getTypeFile`),l=o.isDirectory?null:Lt(o.size)+` (${o.size.toLocaleString()} ${r(`workspace.bytes`)})`,u=o.mimeType||null,d=ty(o.mode,o.isDirectory),f=[[r(`workspace.infoName`),Z(o.name),o.name],[r(`workspace.infoType`),c,c],[r(`workspace.infoPath`),`<span style="word-break:break-all;">${Z(o.path)}</span>`,o.path],[r(`workspace.infoSize`),l||`—`,l],[r(`workspace.infoMime`),u?Z(u):`—`,u],[r(`workspace.infoMtime`),s(o.mtime),s(o.mtime)],[r(`workspace.infoCtime`),s(o.ctime),s(o.ctime)],[r(`workspace.infoAtime`),s(o.atime),s(o.atime)],[r(`workspace.infoPermission`),Z(d),d]];o.uid!==void 0&&f.push([`UID`,String(o.uid),String(o.uid)]),o.gid!==void 0&&f.push([`GID`,String(o.gid),String(o.gid)]),n.className=`file-info-body`,n.innerHTML=`<table class="file-info-table">${f.map(([e,t,n])=>n==null?`<tr><td class="file-info-key">${e}</td><td class="file-info-val">${t}</td></tr>`:`<tr><td class="file-info-key">${e}</td><td class="file-info-val file-info-copyable" data-copy="${Z(n)}" title="${r(`workspace.clickToCopy`)}">${t}<svg class="file-info-copy-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="12" height="12"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></td></tr>`).join(``)}</table>`,n.querySelectorAll(`.file-info-copyable`).forEach(e=>{e.addEventListener(`click`,async()=>{let t=e.dataset.copy;if(t)try{await navigator.clipboard.writeText(t),
|
|
1191
|
+
</div>`,document.body.appendChild(i);let o=()=>i.remove();i.querySelector(`.modal-btn-cancel`).addEventListener(`click`,o),i.querySelector(`.file-info-close`).addEventListener(`click`,o);try{let t=await Rt(e),n=i.querySelector(`.file-info-loading`);if(!t.success||!t.info){n.className=``,n.innerHTML=`<div class="workspace-panel-error">${r(`workspace.getDetailsFailed`,{error:t.error||r(`workspace.unknownError`)})}</div>`;return}let o=t.info,s=e=>e?new Date(e).toLocaleString(a()===`en`?`en-US`:`zh-CN`):`—`,c=o.isDirectory?r(`workspace.getTypeDir`):o.isSymbolicLink?r(`workspace.getTypeSymlink`):r(`workspace.getTypeFile`),l=o.isDirectory?null:Lt(o.size)+` (${o.size.toLocaleString()} ${r(`workspace.bytes`)})`,u=o.mimeType||null,d=ty(o.mode,o.isDirectory),f=[[r(`workspace.infoName`),Z(o.name),o.name],[r(`workspace.infoType`),c,c],[r(`workspace.infoPath`),`<span style="word-break:break-all;">${Z(o.path)}</span>`,o.path],[r(`workspace.infoSize`),l||`—`,l],[r(`workspace.infoMime`),u?Z(u):`—`,u],[r(`workspace.infoMtime`),s(o.mtime),s(o.mtime)],[r(`workspace.infoCtime`),s(o.ctime),s(o.ctime)],[r(`workspace.infoAtime`),s(o.atime),s(o.atime)],[r(`workspace.infoPermission`),Z(d),d]];o.uid!==void 0&&f.push([`UID`,String(o.uid),String(o.uid)]),o.gid!==void 0&&f.push([`GID`,String(o.gid),String(o.gid)]),n.className=`file-info-body`,n.innerHTML=`<table class="file-info-table">${f.map(([e,t,n])=>n==null?`<tr><td class="file-info-key">${e}</td><td class="file-info-val">${t}</td></tr>`:`<tr><td class="file-info-key">${e}</td><td class="file-info-val file-info-copyable" data-copy="${Z(n)}" title="${r(`workspace.clickToCopy`)}">${t}<svg class="file-info-copy-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="12" height="12"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></td></tr>`).join(``)}</table>`,n.querySelectorAll(`.file-info-copyable`).forEach(e=>{e.addEventListener(`click`,async()=>{let t=e.dataset.copy;if(t)try{await navigator.clipboard.writeText(t),P(r(`workspace.copiedToClipboard`),`success`)}catch{P(r(`workspace.copyFailed`),`error`)}})})}catch(e){let t=i.querySelector(`.file-info-loading`);t.className=``,t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.getDetailsFailed`,{error:e.message})}</div>`}}function ry(e,t=``,n=``){return new Promise(i=>{let a=document.createElement(`div`);a.className=`modal-overlay show`,a.innerHTML=`
|
|
1192
1192
|
<div class="modal-container input-dialog" style="min-width:320px;">
|
|
1193
1193
|
<div class="modal-title">${Z(e)}</div>
|
|
1194
1194
|
<input type="text" class="modal-input" value="${Z(t)}" placeholder="${Z(n)}" autofocus style="width:100%;padding:8px 12px;border:1px solid var(--border-default);border-radius:6px;font-size:14px;margin:8px 0;box-sizing:border-box;">
|
|
@@ -1196,7 +1196,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1196
1196
|
<button class="modal-btn-cancel" style="padding:6px 16px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);cursor:pointer;">${r(`workspace.cancel`)}</button>
|
|
1197
1197
|
<button class="modal-btn-confirm" style="padding:6px 16px;border:none;border-radius:6px;background:var(--info-500);color:var(--text-inverse);cursor:pointer;">${r(`workspace.confirm`)}</button>
|
|
1198
1198
|
</div>
|
|
1199
|
-
</div>`,document.body.appendChild(a);let o=a.querySelector(`.modal-input`),s=a.querySelector(`.modal-btn-confirm`),c=a.querySelector(`.modal-btn-cancel`),l=()=>{a.remove()},u=()=>{let e=o.value.trim();l(),i(e||null)};s.addEventListener(`click`,u),c.addEventListener(`click`,()=>{l(),i(null)}),o.addEventListener(`keydown`,e=>{e.key===`Enter`&&u(),e.key===`Escape`&&(l(),i(null))}),setTimeout(()=>o.select(),50)})}async function iy(e={}){let t=e.sessionId===void 0?C.activeSessionId||null:e.sessionId;if(Qm(t))return
|
|
1199
|
+
</div>`,document.body.appendChild(a);let o=a.querySelector(`.modal-input`),s=a.querySelector(`.modal-btn-confirm`),c=a.querySelector(`.modal-btn-cancel`),l=()=>{a.remove()},u=()=>{let e=o.value.trim();l(),i(e||null)};s.addEventListener(`click`,u),c.addEventListener(`click`,()=>{l(),i(null)}),o.addEventListener(`keydown`,e=>{e.key===`Enter`&&u(),e.key===`Escape`&&(l(),i(null))}),setTimeout(()=>o.select(),50)})}async function iy(e={}){let t=e.sessionId===void 0?C.activeSessionId||null:e.sessionId;if(Qm(t))return P(r(`workdirTag.lockedHint`),`warning`),!1;let n=null;try{n=await Mt(t)}catch{return P(r(`workspace.getWorkdirInfoFailed`),`error`),!1}if(!n)return P(r(`workspace.cannotConnectAgent`),`error`),!1;let a=!!t&&n.sessionWorkdirSupported===!0,o=!!(a&&n.sessionWorkdir),s=r(o?`workdirTag.sessionScope`:`workdirTag.defaultScope`),c=n.workdir||``,l=n.defaultWorkdir||c,u=Array.isArray(n.allowedPaths)?[...n.allowedPaths]:[],d=(e,t)=>String(e||``).replace(/\\/g,`/`).toLowerCase()===String(t||``).replace(/\\/g,`/`).toLowerCase(),f=()=>{let e=[...u],t=t=>{t&&!e.some(e=>d(e,t))&&e.push(t)};return t(l),t(c),e},p=!1;try{let e=await jt(),t=e&&e.url?new URL(e.url).hostname:``;p=t===`localhost`||t===`127.0.0.1`||t===`[::1]`}catch(e){i.debug(`[WorkspacePanel] detect local agent failed:`,e)}let m=n.platform||`linux`,h=n.platformName||m,g=n.hostname||``;return new Promise(e=>{let n=document.createElement(`div`);n.className=`modal-overlay show`,n.innerHTML=`
|
|
1200
1200
|
<div class="modal-container switch-workdir-dialog" style="max-width:480px;width:90%;box-sizing:border-box;position:relative;">
|
|
1201
1201
|
<button class="switch-workdir-close" title="${r(`workspace.close`)}" style="position:absolute;top:10px;right:12px;width:28px;height:28px;border:none;background:transparent;color:var(--text-tertiary);border-radius:6px;font-size:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;line-height:1;padding:0;transition:all 0.2s;">✕</button>
|
|
1202
1202
|
<div class="modal-title">${r(a?`workdirTag.switchTitle`:`workspace.switchWorkdirTitle`)}</div>
|
|
@@ -1217,13 +1217,13 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1217
1217
|
<button class="switch-workdir-cancel" style="padding:6px 16px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);cursor:pointer;">${r(`workspace.cancel`)}</button>
|
|
1218
1218
|
<button class="switch-workdir-confirm" style="padding:6px 16px;border:none;border-radius:6px;background:var(--info-500);color:var(--text-inverse);cursor:pointer;">${r(`workspace.switchBtn`)}</button>
|
|
1219
1219
|
</div>
|
|
1220
|
-
</div>`,document.body.appendChild(n);let i=n.querySelector(`#switchWorkdirList`),_=n.querySelector(`.switch-workdir-list-label`),v=n.querySelector(`.switch-workdir-browser`),y=n.querySelector(`.switch-workdir-manual`),b=n.querySelector(`.switch-workdir-cancel`),x=n.querySelector(`.switch-workdir-confirm`),S=n.querySelector(`.switch-workdir-close`),C=n.querySelector(`.switch-workdir-browse`),w=n.querySelector(`.switch-workdir-restore`),T=n.querySelector(`.switch-workdir-set-default`),E=e=>{e&&(y.value=e,y.focus())};async function D(){let e=C.textContent;C.disabled=!0,C.textContent=r(`workspace.picking`);try{let e=await bt();!e.success&&e.error===`busy`&&e.cancellable&&(await Ht(),e=await bt());let t=typeof e.error==`string`?e.error:``;e.success&&e.path?E(e.path):e.success||t===`cancelled`||(e.outdated?
|
|
1220
|
+
</div>`,document.body.appendChild(n);let i=n.querySelector(`#switchWorkdirList`),_=n.querySelector(`.switch-workdir-list-label`),v=n.querySelector(`.switch-workdir-browser`),y=n.querySelector(`.switch-workdir-manual`),b=n.querySelector(`.switch-workdir-cancel`),x=n.querySelector(`.switch-workdir-confirm`),S=n.querySelector(`.switch-workdir-close`),C=n.querySelector(`.switch-workdir-browse`),w=n.querySelector(`.switch-workdir-restore`),T=n.querySelector(`.switch-workdir-set-default`),E=e=>{e&&(y.value=e,y.focus())};async function D(){let e=C.textContent;C.disabled=!0,C.textContent=r(`workspace.picking`);try{let e=await bt();!e.success&&e.error===`busy`&&e.cancellable&&(await Ht(),e=await bt());let t=typeof e.error==`string`?e.error:``;e.success&&e.path?E(e.path):e.success||t===`cancelled`||(e.outdated?P(r(`workspace.browseAgentOutdated`),`error`):t===`busy`?P(r(`workspace.browseBusy`),`info`):t===`timeout`||t===`client-timeout`?P(r(`workspace.browseTimeout`),`info`,5e3):/^(no-dialog-tool|no-display|remote-source)/.test(t)?P(r(`workspace.browseUnavailable`),`info`):P(r(`workspace.browseFailedWithError`,{error:t||r(`workspace.unknownError`)}),`error`,8e3))}catch(e){P(r(`workspace.browseFailedWithError`,{error:e.message||e}),`error`)}finally{C.disabled=!1,C.textContent=e}}let O=v?Zm({container:v,t:r,platform:m,platformName:h,hostname:g,listDirs:Wt,canUseNative:p,onUseNative:()=>{D()},onSelect:e=>{E(e)},onClose:()=>{v.hidden=!0,i&&(i.hidden=!1),_&&(_.hidden=!1),y.focus()}}):null;C&&O&&C.addEventListener(`click`,()=>{i&&(i.hidden=!0),_&&(_.hidden=!0),v.hidden=!1,O.open(y.value.trim()||c||``),C.blur()});let k=e=>{e.key===`Escape`&&O&&O.isOpen()&&(e.preventDefault(),e.stopPropagation(),O.close())};document.addEventListener(`keydown`,k,!0);let A=!1,j=()=>{A||(A=!0,document.removeEventListener(`keydown`,k,!0),O&&O.destroy(),n.remove())};function M(){let e=f();if(!e.length){i.innerHTML=`<div style="padding:16px;text-align:center;color:var(--text-disabled);font-size:13px;">`+r(`workspace.noAllowedPaths`)+`</div>`;return}i.innerHTML=e.map(e=>{let t=d(e,c),n=d(e,l),i=u.some(t=>d(t,e)),a=`<span style="flex-shrink:0;font-size:11px;color:var(--info-500);border:1px solid var(--info-500);border-radius:4px;padding:0 6px;">`+r(`workspace.currentTag`)+`</span>`,o=`<span style="flex-shrink:0;font-size:11px;color:var(--text-tertiary);border:1px solid var(--border-default);border-radius:4px;padding:0 6px;">`+r(`workspace.defaultTag`)+`</span>`;return`
|
|
1221
1221
|
<div class="switch-workdir-item${t?` current`:``}" data-path="${Z(e)}" title="${Z(e)}" style="display:flex;align-items:center;gap:8px;padding:8px 12px;cursor:${t?`default`:`pointer`};font-size:13px;color:${t?`var(--text-tertiary)`:`var(--text-primary)`};word-break:break-all;border-bottom:1px solid var(--bg-subtle);${t?`background:var(--bg-subtle);`:``}">
|
|
1222
1222
|
<span style="flex-shrink:0;">📁</span>
|
|
1223
1223
|
<span style="flex:1;">${Z(e)}</span>
|
|
1224
1224
|
${t?a:``}${n?o:``}
|
|
1225
1225
|
${i?`<button class="switch-workdir-remove" data-remove-path="${Z(e)}" title="${r(`workspace.removeFromAllowed`)}" style="flex-shrink:0;background:none;border:none;color:var(--danger-500);cursor:pointer;font-size:16px;line-height:1;padding:2px 6px;border-radius:4px;">×</button>`:``}
|
|
1226
|
-
</div>`}).join(``)}M(),T&&T.addEventListener(`change`,()=>{i.querySelectorAll(`.switch-workdir-item.current`).forEach(e=>{e.style.cursor=ee(e.dataset.path)?`pointer`:`default`})});async function N(e){let t=d(e,l)||d(e,c);if(!await window.showCustomConfirm(r(t?`workspace.confirmRemoveStillUsable`:`workspace.confirmRemovePath`,{path:e}),r(`workspace.confirmRemovePathTitle`)))return;let n=await Et(e);n.success?(u=Array.isArray(n.allowedPaths)?n.allowedPaths:u.filter(t=>t!==e),M(),F(r(t?`workspace.removedStillUsable`:`workspace.removedFromAllowed`),`success`)):F(r(`workspace.removeFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}let ee=e=>{if(!(T&&T.checked))return!1;let t=e=>String(e||``).replace(/\\/g,`/`).toLowerCase();return!l||t(e)!==t(l)};i.addEventListener(`click`,e=>{let t=e.target.closest(`.switch-workdir-remove`);if(t){e.stopPropagation(),N(t.dataset.removePath);return}let n=e.target.closest(`.switch-workdir-item`);n&&(n.classList.contains(`current`)&&!ee(n.dataset.path)||te(n.dataset.path))});async function te(n){if(!n){F(r(`workspace.selectOrInputPath`),`error`);return}n=n.trim();let i=e=>e.replace(/\\/g,`/`).toLowerCase(),o=(e,t)=>!!e&&!!t&&i(e)===i(t),s=!!(T&&T.checked);if(o(n,c)){if(s&&!o(n,l)){j(),e(await uy(n));return}F(r(`workspace.alreadyCurrentWorkdir`),`info`),j(),e(!1);return}let d=a?t:null,f=!d||s;!u.some(e=>{let t=i(n),r=i(e);return t===r||t.startsWith(r+`/`)})&&f&&!await window.showCustomConfirm(r(`workspace.confirmSwitchToNewDefault`,{path:n}),r(`workspace.confirmSwitchToNewTitle`))||(j(),e(await dy(n,{sessionId:d,setAsDefault:s})))}w&&w.addEventListener(`click`,async()=>{w.disabled=!0,j(),e(await fy(t,{sessionSupported:a}))}),x.addEventListener(`click`,()=>te(y.value)),b.addEventListener(`click`,()=>{j(),e(!1)}),S.addEventListener(`click`,()=>{j(),e(!1)}),S.addEventListener(`mouseenter`,()=>{S.style.color=`var(--text-primary)`,S.style.background=`var(--border-subtle)`}),S.addEventListener(`mouseleave`,()=>{S.style.color=`var(--text-tertiary)`,S.style.background=`transparent`}),y.addEventListener(`keydown`,t=>{t.key===`Enter`&&(t.preventDefault(),te(y.value)),t.key===`Escape`&&(j(),e(!1))}),n.addEventListener(`click`,e=>{e.target===n&&e.stopPropagation()}),setTimeout(()=>y.focus(),50)})}function ay(){ch=null,J=null,lh=[],Y.clear(),Uv=``,Wv=[],Gv=!1,tg.clear();let e=document.getElementById(`workspaceSearchInput`);e&&(e.value=``);let t=document.getElementById(`workspaceSearchClear`);t&&(t.style.display=`none`);let n=document.getElementById(`workspaceToolbar`);if(n){n.classList.remove(`search-focused`);let e=n.querySelector(`.workspace-search-box`);e&&e.classList.remove(`search-box-expanded`)}}var oy=0;async function sy(){let e=++oy;if(C.agentPlatform?.connected!==!0){xt(),ay();return}await Sv();let t=ch;xt();let n=null;try{n=await Kt()}catch(e){i.warn(`[WorkspacePanel] resolve root for session failed:`,e?.message||e)}if(e!==oy||t&&n&&t===n)return;ay();let r=document.getElementById(`workspacePreviewArea`);if(r&&r.dataset.previewPath&&(Dh=!1,await Q_(!0)),await Promise.resolve(),e!==oy)return;let a=document.getElementById(`workspacePanel`);!a||!a.classList.contains(`expanded`)||await $h()}async function cy(e,t){document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:t}}))}async function ly(e){C.defaultWorkdir=e,C.agentPlatform&&={...C.agentPlatform,workdir:e};try{let{activeAgentId:t}=await chrome.storage.local.get([`activeAgentId`]);t&&(C.agentWorkdirs.set(t,e),typeof window.updateAgentItemWorkdir==`function`&&window.updateAgentItemWorkdir(t,e))}catch(e){i.debug(`[WorkspacePanel] sync dropdown column table workdir failed:`,e)}}async function uy(e){let t=await yt(e,{sessionId:null});return t.success?(await ly(t.workdir),await cy(null,t.workdir),F(r(`workspace.setAsDefaultDone`,{path:t.workdir}),`success`),!0):(F(r(`workspace.switchFailedWithError`,{error:t.error||r(`workspace.unknownError`)}),`error`),!1)}async function dy(e,t={}){let n=t.sessionId===void 0?C.activeSessionId||null:t.sessionId,a=t.setAsDefault===!0,o=await yt(e,{sessionId:n});if(!o.success)return F(r(`workspace.switchFailedWithError`,{error:o.error||r(`workspace.unknownError`)}),`error`),!1;if(n)try{let{setSessionWorkdirBinding:e}=await A(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-DfBABQNR.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([12,1,2,3])),t=(await jt())?.id||null;await e(n,o.workdir,t)}catch(e){i.warn(`[WorkspacePanel] persist session workdir failed:`,e)}let s=!1;if(a){let e=await yt(o.workdir,{sessionId:null});e.success?s=!0:F(r(`workspace.switchFailedWithError`,{error:e.error||r(`workspace.unknownError`)}),`error`)}return(!n||a)&&await ly(o.workdir),await cy(n,o.workdir),F(r(s?`workspace.switchedToAndSetDefault`:`workspace.switchedTo`,{path:o.workdir}),`success`),!0}async function fy(e,t={}){if(!e)return!1;let{unbindSessionWorkdirRemote:n}=await A(async()=>{let{unbindSessionWorkdirRemote:e}=await import(`./model-profiles-CqsAD3Fd.js`).then(e=>e.z);return{unbindSessionWorkdirRemote:e}},__vite__mapDeps([2,1,3]));if(await n(e)===null&&t.sessionSupported)return F(r(`workspace.switchFailedWithError`,{error:r(`workspace.unknownError`)}),`error`),!1;try{let{setSessionWorkdirBinding:t}=await A(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-DfBABQNR.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([12,1,2,3]));await t(e,null,null)}catch(e){i.warn(`[WorkspacePanel] clear session workdir failed:`,e)}return await cy(e,``),F(r(`workdirTag.restoredDefault`),`success`),!0}async function py(e,t,n){let i=t,a=``,o=t.lastIndexOf(`.`);n!==`directory`&&o>0&&(i=t.substring(0,o),a=t.substring(o));let s=await ry(r(n===`directory`?`workspace.renameDir`:`workspace.renameFile`),i,r(`workspace.inputNewName`));if(!s||s===i)return;let c=s+a;try{let t=await St(e,c);t.success?(F(r(`workspace.renamedTo`,{name:c}),`success`),cg(J),await Tv(),vy(c)):F(r(`workspace.renameFailedWithError`,{error:t.error}),`error`)}catch(e){F(r(`workspace.renameFailedWithError`,{error:e.message}),`error`)}}async function my(){if(!J)return;let e=await ry(r(`workspace.newFolderTitle`),``,r(`workspace.inputFolderName`));if(!e)return;let t=sg(`${J}/${e}`);try{let n=await Ft(t);n.success?(F(r(`workspace.folderCreated`,{name:e}),`success`),cg(J),await Tv(),vy(e)):F(r(`workspace.createFailedWithError`,{error:n.error}),`error`)}catch(e){F(r(`workspace.createFailedWithError`,{error:e.message}),`error`)}}async function hy(e){return new Promise((t,n)=>{let i=new Image,a=URL.createObjectURL(e);i.onload=()=>{URL.revokeObjectURL(a);let n=new FileReader;n.onloadend=()=>{let e=n.result,r=i.width,a=i.height,o=Math.max(r,a),s,c;o<=768?(s=o,c=.75):o<=1280?(s=768,c=.7):o<=2560?(s=1024,c=.65):o<=3840?(s=1280,c=.6):(s=1280,c=.55);let l=r,u=a;o>s&&(r>a?(u=Math.round(s/r*a),l=s):(l=Math.round(s/a*r),u=s));let d=document.createElement(`canvas`);d.width=l,d.height=u;let f=d.getContext(`2d`);f.imageSmoothingEnabled=!0,f.imageSmoothingQuality=`high`,f.drawImage(i,0,0,l,u),t({originalUrl:e,compressedUrl:d.toDataURL(`image/jpeg`,c)})},n.readAsDataURL(e)},i.onerror=()=>{URL.revokeObjectURL(a),n(Error(r(`workspace.imageLoadFailed`)))},i.src=a})}async function gy(e){let t=[],n=[];for(let r of e){let e=r&&typeof r==`object`,i=e?r.fullPath||r.path:r,a=i.split(/[\\/]/).pop(),o;e?o=r:(o=Mh.find(e=>e.path===i),o||=Wv.find(e=>e.fullPath===i));let s=o?o.size:0,c=Nt(a);if(c.startsWith(`image/`)&&C.enableImageInput)n.push({name:a,size:s,type:c,path:i});else{let e={name:a,size:s,type:c,text:``,status:`done`,agentPath:i};t.push(e)}}for(let e of n)try{let t=await jt();if(t){let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(t)},body:JSON.stringify({path:e.path})});if(n.ok){let{originalUrl:e,compressedUrl:t}=await hy(await n.blob());C.attachedImages.some(e=>e.compressedUrl===t)||C.attachedImages.push({originalUrl:e,compressedUrl:t})}}}catch{}for(let e of t)C.attachedFiles.some(t=>t.name===e.name&&t.agentPath===e.agentPath)||C.attachedFiles.push(e);Am(),nh();let i=t.length+n.length;i>0&&(!C.enableImageInput&&t.some(e=>e.type?.startsWith(`image/`))?F(r(`workspace.addedFilesToQuestionNoImage`,{count:i}),`success`):F(r(`workspace.addedFilesToQuestion`,{count:i}),`success`))}async function _y(){Y.size!==0&&await gy(Array.from(Y))}function vy(e,t=0){let n=document.getElementById(`workspacePanelContent`);if(!n)return;if(fg){let t=fg.sorted.findIndex(t=>t.name===e);if(t>=0){let r=fg.itemHeight;n.scrollTop=Math.max(0,t*r-n.clientHeight/2+r/2),hg();let i=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);i&&(i.classList.add(`highlight-new`),setTimeout(()=>i.classList.remove(`highlight-new`),2e3));return}}let r=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);r?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`highlight-new`),setTimeout(()=>r.classList.remove(`highlight-new`),2e3)):t<5&&setTimeout(()=>vy(e,t+1),150)}function yy(){let e=document.getElementById(`workspaceAskBtn`);Y.size===0?e.style.display=`none`:e.style.display=``}function by(){let e=document.getElementById(`workspaceDownloadDirBtn`),t=document.getElementById(`workspaceBatchDeleteBtn`),n=document.getElementById(`workspaceSelectedCount`);Y.size===0?(e.style.display=`none`,t.style.display=`none`,n.style.display=`none`):(e.style.display=``,t.style.display=``,n.style.display=``,n.textContent=r(`workspace.selectedCount`,{count:Y.size}),e.disabled=wh),yy()}n(`zh`,{artifacts:{btnTitle:`文件产物({count})`,modalTitle:`本次任务的文件产物`,emptyHint:`本次任务没有产生文件产物`,fileCol:`文件`,sizeCol:`大小`,typeCol:`类型`,timeCol:`时间`,actionCol:`操作`,locate:`定位到文件`,preview:`预览`,closeBtn:`关闭`,typeWrite:`写入`,typeDelete:`删除`,typeCreate:`创建`,typeEdit:`编辑`,typeOther:`操作`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,locateFailed:`定位文件失败`,fileNotFound:`目录已定位,但未找到该文件(可能已被删除)`,previewFailed:`预览文件失败`,previewNotSupported:`此文件类型不支持预览`,totalCount:`共 {count} 个文件`,badgeLabel:`产物`,download:`下载`,downloadFailed:`下载失败`,copyFileName:`复制文件名`,copyFilePath:`复制文件路径`,copiedName:`已复制文件名:{name}`,copiedPath:`已复制文件路径`,dblClickHint:`双击文件名可预览`,sortHint:`点击排序`,serialCol:`序号`}}),n(`en`,{artifacts:{btnTitle:`Artifacts ({count})`,modalTitle:`File Artifacts of This Task`,emptyHint:`No file artifacts produced in this task`,fileCol:`File`,sizeCol:`Size`,typeCol:`Type`,timeCol:`Time`,actionCol:`Actions`,locate:`Locate File`,preview:`Preview`,closeBtn:`Close`,typeWrite:`Write`,typeDelete:`Delete`,typeCreate:`Create`,typeEdit:`Edit`,typeOther:`Op`,noWorkspace:`Unable to access working directory. Please confirm the Agent is connected.`,locateFailed:`Failed to locate file`,fileNotFound:`Directory located, but file not found (may have been deleted)`,previewFailed:`Failed to preview file`,previewNotSupported:`Preview not supported for this file type`,totalCount:`{count} files in total`,badgeLabel:`Artifacts`,download:`Download`,downloadFailed:`Download failed`,copyFileName:`Copy File Name`,copyFilePath:`Copy File Path`,copiedName:`Copied file name: {name}`,copiedPath:`File path copied`,dblClickHint:`Double-click to preview`,sortHint:`Click to sort`,serialCol:`#`}});function Q(e){let t=(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`),n=t.replace(/\/+$/,``);return n?/^[A-Za-z]:$/.test(n)?n+`/`:n:t?`/`:``}function xy(e){if(!e)return``;let t=Q(e).replace(/\/+$/,``).split(`/`);return t[t.length-1]||``}function Sy(e){if(!e)return``;let t=xy(e),n=t.lastIndexOf(`.`);return n>0?t.substring(n+1).toLowerCase():``}function Cy(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function wy(e,t){let n=new Set(t),r=[],i=0,a=``;for(let t of e)t===`{`?i++:t===`}`&&(i=Math.max(0,i-1)),i===0&&n.has(t)?(r.push(a),a=``):a+=t;return r.push(a),r}function Ty(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=0,r=-1;for(let i=t;i<e.length;i++)if(e[i]===`{`)n++;else if(e[i]===`}`&&(n--,n===0)){r=i;break}if(r===-1)return[e];let i=e.substring(0,t),a=e.substring(t+1,r),o=e.substring(r+1),s=wy(a,`,`).map(e=>e.trim());if(s.length<=1)return[e];let c=[];for(let e of s)for(let t of Ty(e))for(let e of Ty(o))c.push(i+t+e);return c}function Ey(e,t){let n=[],r=new Set;for(let i of e)if(i)for(let e of Ty(i)){if(!e)continue;let i=t(e);!i||r.has(i)||(r.add(i),n.push(i))}return n}function Dy(e){if(!e)return null;let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{let e=t.match(/["']?path["']?\s*[:=]\s*["']([^"']+)["']/i);return e?e[1]:null}return t&&typeof t==`object`&&(t.path||t.filePath||t.file_path||t.result?.path)||null}function Oy(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`?n++:a===`}`&&(n=Math.max(0,n-1)),n===0&&a===`<`&&e[i+1]===`<`){let t=ky(e,i);if(t>i){r+=e.substring(i,t),i=t-1;continue}}n===0&&a===`;`?(t.push(r),r=``):n===0&&a===`&`&&e[i+1]===`&`?(t.push(r),r=``,i++):r+=a}return t.push(r),t}function ky(e,t){let n=e.substring(t).match(/^<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/);if(!n)return-1;let r=n[1],i=t+n[0].length,a=e.substring(i),o=RegExp(`\\n\\s*`+r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)+`\\s*(?=\\n|$)`),s=a.match(o);return s?i+s.index+s[0].length:-1}function Ay(e){let t=Q(e||``).replace(/\/$/,``);if(!t)return``;let n=t.lastIndexOf(`/`);return n>0?t.substring(0,n):``}var jy=new Set([`du`,`df`,`stat`,`wc`,`file`,`cat`,`head`,`tail`,`grep`,`rg`]);function My(e){if(!e||typeof e!=`string`)return!1;let t=Oy(e);if(t.length===0)return!1;for(let e of t){let t=e.trim().split(/\s+/).filter(Boolean);for(;t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0]);)t.shift();if(!t.length)continue;let n=t[0].split(`/`).pop().toLowerCase();if(n===`sudo`&&t.length>1&&(n=t[1].split(`/`).pop().toLowerCase()),!jy.has(n))return!1}return!0}function Ny(e,t){let n=t=>e===t||e.startsWith(t.endsWith(`/`)?t:t+`/`);return[...t].some(n)}function Py(e,t){if(!e||typeof e!=`string`)return t||``;let n=t||``;for(let t of Oy(e)){let e=t.trim().match(/^cd\s+(.+?)\s*$/);if(!e)continue;let r=e[1].trim().replace(/^['"]|['"]$/g,``);n=r.startsWith(`/`)||r.startsWith(`~/`)?r:r===`..`?n?Q(n).replace(/\/[^/]+$/,``)||`/`:`..`:Q(n?n.replace(/\/$/,``)+`/`+r:r)}return n}function Fy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=Oy(e);for(let e of i){let t=e.trim();if(!t)continue;let i=t.replace(/"[^"]*"/g,`""`).replace(/'[^']*'/g,`''`),a=t.match(/^cd\s+(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||e.startsWith(`~/`)?e:e===`..`?r?Q(r).replace(/\/[^/]+$/,``)||`/`:`..`:Q(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&r&&(e=Q(r.replace(/\/$/,``)+`/`+e)),Q(e)),s=t.match(/^(\S+)\s+.*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*$/);if(s){let e=s[1].split(`/`).pop().toLowerCase(),t=s[3],r=null;if(/^python[\d.]*$/.test(e)?r=`py`:/^(ba)?sh$/.test(e)&&(r=`sh`),r){for(let e of Iy(t,r))e&&n.push({path:o(e),isDir:!1});continue}}let c=i.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(c){let e=Ey(wy(c[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!0});continue}let l=i.match(/^touch\s+(.+)$/);if(l){let e=Ey(wy(l[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!1});continue}let u=null,d=i.match(/\s[>]{1,2}\s*['"]?([^\s|&;'"]+)['"]?\s*$/);if(d&&(u=d[1]),!u){let e=i.match(/^cat\s+>\s*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(!u){let e=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);e&&(u=e[1])}if(!u){let e=i.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(u){let e=Ey([u],o);for(let t of e)n.push({path:t,isDir:!1})}}return n}function Iy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=e.split(`
|
|
1226
|
+
</div>`}).join(``)}M(),T&&T.addEventListener(`change`,()=>{i.querySelectorAll(`.switch-workdir-item.current`).forEach(e=>{e.style.cursor=ee(e.dataset.path)?`pointer`:`default`})});async function N(e){let t=d(e,l)||d(e,c);if(!await window.showCustomConfirm(r(t?`workspace.confirmRemoveStillUsable`:`workspace.confirmRemovePath`,{path:e}),r(`workspace.confirmRemovePathTitle`)))return;let n=await Et(e);n.success?(u=Array.isArray(n.allowedPaths)?n.allowedPaths:u.filter(t=>t!==e),M(),P(r(t?`workspace.removedStillUsable`:`workspace.removedFromAllowed`),`success`)):P(r(`workspace.removeFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}let ee=e=>{if(!(T&&T.checked))return!1;let t=e=>String(e||``).replace(/\\/g,`/`).toLowerCase();return!l||t(e)!==t(l)};i.addEventListener(`click`,e=>{let t=e.target.closest(`.switch-workdir-remove`);if(t){e.stopPropagation(),N(t.dataset.removePath);return}let n=e.target.closest(`.switch-workdir-item`);n&&(n.classList.contains(`current`)&&!ee(n.dataset.path)||te(n.dataset.path))});async function te(n){if(!n){P(r(`workspace.selectOrInputPath`),`error`);return}n=n.trim();let i=e=>e.replace(/\\/g,`/`).toLowerCase(),o=(e,t)=>!!e&&!!t&&i(e)===i(t),s=!!(T&&T.checked);if(o(n,c)){if(s&&!o(n,l)){j(),e(await uy(n));return}P(r(`workspace.alreadyCurrentWorkdir`),`info`),j(),e(!1);return}let d=a?t:null,f=!d||s;!u.some(e=>{let t=i(n),r=i(e);return t===r||t.startsWith(r+`/`)})&&f&&!await window.showCustomConfirm(r(`workspace.confirmSwitchToNewDefault`,{path:n}),r(`workspace.confirmSwitchToNewTitle`))||(j(),e(await dy(n,{sessionId:d,setAsDefault:s})))}w&&w.addEventListener(`click`,async()=>{w.disabled=!0,j(),e(await fy(t,{sessionSupported:a}))}),x.addEventListener(`click`,()=>te(y.value)),b.addEventListener(`click`,()=>{j(),e(!1)}),S.addEventListener(`click`,()=>{j(),e(!1)}),S.addEventListener(`mouseenter`,()=>{S.style.color=`var(--text-primary)`,S.style.background=`var(--border-subtle)`}),S.addEventListener(`mouseleave`,()=>{S.style.color=`var(--text-tertiary)`,S.style.background=`transparent`}),y.addEventListener(`keydown`,t=>{t.key===`Enter`&&(t.preventDefault(),te(y.value)),t.key===`Escape`&&(j(),e(!1))}),n.addEventListener(`click`,e=>{e.target===n&&e.stopPropagation()}),setTimeout(()=>y.focus(),50)})}function ay(){ch=null,J=null,lh=[],Y.clear(),Uv=``,Wv=[],Gv=!1,tg.clear();let e=document.getElementById(`workspaceSearchInput`);e&&(e.value=``);let t=document.getElementById(`workspaceSearchClear`);t&&(t.style.display=`none`);let n=document.getElementById(`workspaceToolbar`);if(n){n.classList.remove(`search-focused`);let e=n.querySelector(`.workspace-search-box`);e&&e.classList.remove(`search-box-expanded`)}}var oy=0;async function sy(){let e=++oy;if(C.agentPlatform?.connected!==!0){xt(),ay();return}await Sv();let t=ch;xt();let n=null;try{n=await Kt()}catch(e){i.warn(`[WorkspacePanel] resolve root for session failed:`,e?.message||e)}if(e!==oy||t&&n&&t===n)return;ay();let r=document.getElementById(`workspacePreviewArea`);if(r&&r.dataset.previewPath&&(Dh=!1,await Q_(!0)),await Promise.resolve(),e!==oy)return;let a=document.getElementById(`workspacePanel`);!a||!a.classList.contains(`expanded`)||await $h()}async function cy(e,t){document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:t}}))}async function ly(e){C.defaultWorkdir=e,C.agentPlatform&&={...C.agentPlatform,workdir:e};try{let{activeAgentId:t}=await chrome.storage.local.get([`activeAgentId`]);t&&(C.agentWorkdirs.set(t,e),typeof window.updateAgentItemWorkdir==`function`&&window.updateAgentItemWorkdir(t,e))}catch(e){i.debug(`[WorkspacePanel] sync dropdown column table workdir failed:`,e)}}async function uy(e){let t=await yt(e,{sessionId:null});return t.success?(await ly(t.workdir),await cy(null,t.workdir),P(r(`workspace.setAsDefaultDone`,{path:t.workdir}),`success`),!0):(P(r(`workspace.switchFailedWithError`,{error:t.error||r(`workspace.unknownError`)}),`error`),!1)}async function dy(e,t={}){let n=t.sessionId===void 0?C.activeSessionId||null:t.sessionId,a=t.setAsDefault===!0,o=await yt(e,{sessionId:n});if(!o.success)return P(r(`workspace.switchFailedWithError`,{error:o.error||r(`workspace.unknownError`)}),`error`),!1;if(n)try{let{setSessionWorkdirBinding:e}=await A(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-DfBABQNR.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([13,1,2,3])),t=(await jt())?.id||null;await e(n,o.workdir,t)}catch(e){i.warn(`[WorkspacePanel] persist session workdir failed:`,e)}let s=!1;if(a){let e=await yt(o.workdir,{sessionId:null});e.success?s=!0:P(r(`workspace.switchFailedWithError`,{error:e.error||r(`workspace.unknownError`)}),`error`)}return(!n||a)&&await ly(o.workdir),await cy(n,o.workdir),P(r(s?`workspace.switchedToAndSetDefault`:`workspace.switchedTo`,{path:o.workdir}),`success`),!0}async function fy(e,t={}){if(!e)return!1;let{unbindSessionWorkdirRemote:n}=await A(async()=>{let{unbindSessionWorkdirRemote:e}=await import(`./model-profiles-CqsAD3Fd.js`).then(e=>e.z);return{unbindSessionWorkdirRemote:e}},__vite__mapDeps([2,1,3]));if(await n(e)===null&&t.sessionSupported)return P(r(`workspace.switchFailedWithError`,{error:r(`workspace.unknownError`)}),`error`),!1;try{let{setSessionWorkdirBinding:t}=await A(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-DfBABQNR.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([13,1,2,3]));await t(e,null,null)}catch(e){i.warn(`[WorkspacePanel] clear session workdir failed:`,e)}return await cy(e,``),P(r(`workdirTag.restoredDefault`),`success`),!0}async function py(e,t,n){let i=t,a=``,o=t.lastIndexOf(`.`);n!==`directory`&&o>0&&(i=t.substring(0,o),a=t.substring(o));let s=await ry(r(n===`directory`?`workspace.renameDir`:`workspace.renameFile`),i,r(`workspace.inputNewName`));if(!s||s===i)return;let c=s+a;try{let t=await St(e,c);t.success?(P(r(`workspace.renamedTo`,{name:c}),`success`),cg(J),await Tv(),vy(c)):P(r(`workspace.renameFailedWithError`,{error:t.error}),`error`)}catch(e){P(r(`workspace.renameFailedWithError`,{error:e.message}),`error`)}}async function my(){if(!J)return;let e=await ry(r(`workspace.newFolderTitle`),``,r(`workspace.inputFolderName`));if(!e)return;let t=sg(`${J}/${e}`);try{let n=await Ft(t);n.success?(P(r(`workspace.folderCreated`,{name:e}),`success`),cg(J),await Tv(),vy(e)):P(r(`workspace.createFailedWithError`,{error:n.error}),`error`)}catch(e){P(r(`workspace.createFailedWithError`,{error:e.message}),`error`)}}async function hy(e){return new Promise((t,n)=>{let i=new Image,a=URL.createObjectURL(e);i.onload=()=>{URL.revokeObjectURL(a);let n=new FileReader;n.onloadend=()=>{let e=n.result,r=i.width,a=i.height,o=Math.max(r,a),s,c;o<=768?(s=o,c=.75):o<=1280?(s=768,c=.7):o<=2560?(s=1024,c=.65):o<=3840?(s=1280,c=.6):(s=1280,c=.55);let l=r,u=a;o>s&&(r>a?(u=Math.round(s/r*a),l=s):(l=Math.round(s/a*r),u=s));let d=document.createElement(`canvas`);d.width=l,d.height=u;let f=d.getContext(`2d`);f.imageSmoothingEnabled=!0,f.imageSmoothingQuality=`high`,f.drawImage(i,0,0,l,u),t({originalUrl:e,compressedUrl:d.toDataURL(`image/jpeg`,c)})},n.readAsDataURL(e)},i.onerror=()=>{URL.revokeObjectURL(a),n(Error(r(`workspace.imageLoadFailed`)))},i.src=a})}async function gy(e){let t=[],n=[];for(let r of e){let e=r&&typeof r==`object`,i=e?r.fullPath||r.path:r,a=i.split(/[\\/]/).pop(),o;e?o=r:(o=Mh.find(e=>e.path===i),o||=Wv.find(e=>e.fullPath===i));let s=o?o.size:0,c=Nt(a);if(c.startsWith(`image/`)&&C.enableImageInput)n.push({name:a,size:s,type:c,path:i});else{let e={name:a,size:s,type:c,text:``,status:`done`,agentPath:i};t.push(e)}}for(let e of n)try{let t=await jt();if(t){let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(t)},body:JSON.stringify({path:e.path})});if(n.ok){let{originalUrl:e,compressedUrl:t}=await hy(await n.blob());C.attachedImages.some(e=>e.compressedUrl===t)||C.attachedImages.push({originalUrl:e,compressedUrl:t})}}}catch{}for(let e of t)C.attachedFiles.some(t=>t.name===e.name&&t.agentPath===e.agentPath)||C.attachedFiles.push(e);Am(),nh();let i=t.length+n.length;i>0&&(!C.enableImageInput&&t.some(e=>e.type?.startsWith(`image/`))?P(r(`workspace.addedFilesToQuestionNoImage`,{count:i}),`success`):P(r(`workspace.addedFilesToQuestion`,{count:i}),`success`))}async function _y(){Y.size!==0&&await gy(Array.from(Y))}function vy(e,t=0){let n=document.getElementById(`workspacePanelContent`);if(!n)return;if(fg){let t=fg.sorted.findIndex(t=>t.name===e);if(t>=0){let r=fg.itemHeight;n.scrollTop=Math.max(0,t*r-n.clientHeight/2+r/2),hg();let i=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);i&&(i.classList.add(`highlight-new`),setTimeout(()=>i.classList.remove(`highlight-new`),2e3));return}}let r=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);r?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`highlight-new`),setTimeout(()=>r.classList.remove(`highlight-new`),2e3)):t<5&&setTimeout(()=>vy(e,t+1),150)}function yy(){let e=document.getElementById(`workspaceAskBtn`);Y.size===0?e.style.display=`none`:e.style.display=``}function by(){let e=document.getElementById(`workspaceDownloadDirBtn`),t=document.getElementById(`workspaceBatchDeleteBtn`),n=document.getElementById(`workspaceSelectedCount`);Y.size===0?(e.style.display=`none`,t.style.display=`none`,n.style.display=`none`):(e.style.display=``,t.style.display=``,n.style.display=``,n.textContent=r(`workspace.selectedCount`,{count:Y.size}),e.disabled=wh),yy()}n(`zh`,{artifacts:{btnTitle:`文件产物({count})`,modalTitle:`本次任务的文件产物`,emptyHint:`本次任务没有产生文件产物`,fileCol:`文件`,sizeCol:`大小`,typeCol:`类型`,timeCol:`时间`,actionCol:`操作`,locate:`定位到文件`,preview:`预览`,closeBtn:`关闭`,typeWrite:`写入`,typeDelete:`删除`,typeCreate:`创建`,typeEdit:`编辑`,typeOther:`操作`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,locateFailed:`定位文件失败`,fileNotFound:`目录已定位,但未找到该文件(可能已被删除)`,previewFailed:`预览文件失败`,previewNotSupported:`此文件类型不支持预览`,totalCount:`共 {count} 个文件`,badgeLabel:`产物`,download:`下载`,downloadFailed:`下载失败`,copyFileName:`复制文件名`,copyFilePath:`复制文件路径`,copiedName:`已复制文件名:{name}`,copiedPath:`已复制文件路径`,dblClickHint:`双击文件名可预览`,sortHint:`点击排序`,serialCol:`序号`}}),n(`en`,{artifacts:{btnTitle:`Artifacts ({count})`,modalTitle:`File Artifacts of This Task`,emptyHint:`No file artifacts produced in this task`,fileCol:`File`,sizeCol:`Size`,typeCol:`Type`,timeCol:`Time`,actionCol:`Actions`,locate:`Locate File`,preview:`Preview`,closeBtn:`Close`,typeWrite:`Write`,typeDelete:`Delete`,typeCreate:`Create`,typeEdit:`Edit`,typeOther:`Op`,noWorkspace:`Unable to access working directory. Please confirm the Agent is connected.`,locateFailed:`Failed to locate file`,fileNotFound:`Directory located, but file not found (may have been deleted)`,previewFailed:`Failed to preview file`,previewNotSupported:`Preview not supported for this file type`,totalCount:`{count} files in total`,badgeLabel:`Artifacts`,download:`Download`,downloadFailed:`Download failed`,copyFileName:`Copy File Name`,copyFilePath:`Copy File Path`,copiedName:`Copied file name: {name}`,copiedPath:`File path copied`,dblClickHint:`Double-click to preview`,sortHint:`Click to sort`,serialCol:`#`}});function Q(e){let t=(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`),n=t.replace(/\/+$/,``);return n?/^[A-Za-z]:$/.test(n)?n+`/`:n:t?`/`:``}function xy(e){if(!e)return``;let t=Q(e).replace(/\/+$/,``).split(`/`);return t[t.length-1]||``}function Sy(e){if(!e)return``;let t=xy(e),n=t.lastIndexOf(`.`);return n>0?t.substring(n+1).toLowerCase():``}function Cy(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function wy(e,t){let n=new Set(t),r=[],i=0,a=``;for(let t of e)t===`{`?i++:t===`}`&&(i=Math.max(0,i-1)),i===0&&n.has(t)?(r.push(a),a=``):a+=t;return r.push(a),r}function Ty(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=0,r=-1;for(let i=t;i<e.length;i++)if(e[i]===`{`)n++;else if(e[i]===`}`&&(n--,n===0)){r=i;break}if(r===-1)return[e];let i=e.substring(0,t),a=e.substring(t+1,r),o=e.substring(r+1),s=wy(a,`,`).map(e=>e.trim());if(s.length<=1)return[e];let c=[];for(let e of s)for(let t of Ty(e))for(let e of Ty(o))c.push(i+t+e);return c}function Ey(e,t){let n=[],r=new Set;for(let i of e)if(i)for(let e of Ty(i)){if(!e)continue;let i=t(e);!i||r.has(i)||(r.add(i),n.push(i))}return n}function Dy(e){if(!e)return null;let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{let e=t.match(/["']?path["']?\s*[:=]\s*["']([^"']+)["']/i);return e?e[1]:null}return t&&typeof t==`object`&&(t.path||t.filePath||t.file_path||t.result?.path)||null}function Oy(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`?n++:a===`}`&&(n=Math.max(0,n-1)),n===0&&a===`<`&&e[i+1]===`<`){let t=ky(e,i);if(t>i){r+=e.substring(i,t),i=t-1;continue}}n===0&&a===`;`?(t.push(r),r=``):n===0&&a===`&`&&e[i+1]===`&`?(t.push(r),r=``,i++):r+=a}return t.push(r),t}function ky(e,t){let n=e.substring(t).match(/^<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/);if(!n)return-1;let r=n[1],i=t+n[0].length,a=e.substring(i),o=RegExp(`\\n\\s*`+r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)+`\\s*(?=\\n|$)`),s=a.match(o);return s?i+s.index+s[0].length:-1}function Ay(e){let t=Q(e||``).replace(/\/$/,``);if(!t)return``;let n=t.lastIndexOf(`/`);return n>0?t.substring(0,n):``}var jy=new Set([`du`,`df`,`stat`,`wc`,`file`,`cat`,`head`,`tail`,`grep`,`rg`]);function My(e){if(!e||typeof e!=`string`)return!1;let t=Oy(e);if(t.length===0)return!1;for(let e of t){let t=e.trim().split(/\s+/).filter(Boolean);for(;t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0]);)t.shift();if(!t.length)continue;let n=t[0].split(`/`).pop().toLowerCase();if(n===`sudo`&&t.length>1&&(n=t[1].split(`/`).pop().toLowerCase()),!jy.has(n))return!1}return!0}function Ny(e,t){let n=t=>e===t||e.startsWith(t.endsWith(`/`)?t:t+`/`);return[...t].some(n)}function Py(e,t){if(!e||typeof e!=`string`)return t||``;let n=t||``;for(let t of Oy(e)){let e=t.trim().match(/^cd\s+(.+?)\s*$/);if(!e)continue;let r=e[1].trim().replace(/^['"]|['"]$/g,``);n=r.startsWith(`/`)||r.startsWith(`~/`)?r:r===`..`?n?Q(n).replace(/\/[^/]+$/,``)||`/`:`..`:Q(n?n.replace(/\/$/,``)+`/`+r:r)}return n}function Fy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=Oy(e);for(let e of i){let t=e.trim();if(!t)continue;let i=t.replace(/"[^"]*"/g,`""`).replace(/'[^']*'/g,`''`),a=t.match(/^cd\s+(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||e.startsWith(`~/`)?e:e===`..`?r?Q(r).replace(/\/[^/]+$/,``)||`/`:`..`:Q(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&r&&(e=Q(r.replace(/\/$/,``)+`/`+e)),Q(e)),s=t.match(/^(\S+)\s+.*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*$/);if(s){let e=s[1].split(`/`).pop().toLowerCase(),t=s[3],r=null;if(/^python[\d.]*$/.test(e)?r=`py`:/^(ba)?sh$/.test(e)&&(r=`sh`),r){for(let e of Iy(t,r))e&&n.push({path:o(e),isDir:!1});continue}}let c=i.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(c){let e=Ey(wy(c[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!0});continue}let l=i.match(/^touch\s+(.+)$/);if(l){let e=Ey(wy(l[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!1});continue}let u=null,d=i.match(/\s[>]{1,2}\s*['"]?([^\s|&;'"]+)['"]?\s*$/);if(d&&(u=d[1]),!u){let e=i.match(/^cat\s+>\s*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(!u){let e=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);e&&(u=e[1])}if(!u){let e=i.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(u){let e=Ey([u],o);for(let t of e)n.push({path:t,isDir:!1})}}return n}function Iy(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=e.split(`
|
|
1227
1227
|
`);if([`sh`,`bash`,`zsh`].includes(t))for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=[...t.matchAll(/[>]{1,2}\s*['"]?([^\s|&;>'"]+)['"]?/g)];for(let e of r)e[1]&&!e[1].startsWith(`/dev/`)&&n.push(e[1]);let i=t.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(i){let e=wy(i[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let a=t.match(/^touch\s+(.+)$/);if(a){let e=wy(a[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let o=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);o&&n.push(o[1]);let s=t.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);s&&n.push(s[1])}else if(t===`bat`||t===`cmd`)for(let e of r){let t=e.trim().replace(/^@/,``);if(!t||(t.toUpperCase(),/^REM\b/i.test(t)||t.startsWith(`::`))||/^ECHO\b/i.test(t)&&!/[>]{1,2}/.test(t))continue;let r=[...t.matchAll(/[>]{1,2}\s*"?([^\s|&;>"]+)"?/g)];for(let e of r)e[1]&&e[1].toUpperCase()!==`NUL`&&n.push(e[1]);let i=t.match(/^(?:mkdir|md)\s+(?:"([^"]+)"|(\S+))/i);i&&n.push(i[1]||i[2]);let a=t.match(/^copy\s+(?:\/\S+\s+)*(?:.+?\s+)+?"?([^\s|&;"]+)"?\s*$/i);a&&n.push(a[1]);let o=t.match(/^xcopy\s+(?:\/\S+\s+)*(?:"[^"]+"|\S+)\s+(?:"([^"]+)"|(\S+))/i);o&&n.push(o[1]||o[2])}else if(t===`ps1`)for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=[...t.matchAll(/[>]{1,2}\s*"?([^\s|;>'"]+)"?/g)];for(let e of r)e[1]&&e[1].toUpperCase()!==`NUL`&&n.push(e[1]);let i=t.match(/(?:Set-Content|Out-File|Add-Content)\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?/i);i&&n.push(i[1]);let a=t.match(/New-Item\s+(?:-[\w]+\s+)*-Path\s+"?([^";\s|]+)"?/i);a&&n.push(a[1]);let o=t.match(/New-Item\s+"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-ItemType/i);o&&n.push(o[1]);let s=t.match(/Copy-Item\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-Destination\s+"?([^";\s|]+)"?/i);s&&n.push(s[2]);let c=t.match(/Move-Item\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-Destination\s+"?([^";\s|]+)"?/i);c&&n.push(c[2])}else if(t===`py`)for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=t.match(/open\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"][wax][+]?['"]/);r&&n.push(r[1]);let i=t.match(/os\.(?:makedirs|mkdir)\s*\(\s*['"]([^'"]+)['"]/);i&&n.push(i[1]);let a=t.match(/shutil\.(?:copy2?|move)\s*\([^,]+,\s*['"]([^'"]+)['"]/);a&&n.push(a[1]);let o=t.match(/Path\s*\(\s*['"]([^'"]+)['"]\s*\)\s*\.\s*(?:write_text|write_bytes|touch|mkdir)/);o&&n.push(o[1])}let i=new Set;return n.filter(e=>!e||i.has(e)||(i.add(e),/\$[\w({]|%[\w]+%/.test(e))?!1:e.includes(`/`)||e.includes(`\\`)||e.includes(`.`))}function Ly(e,t,n){if(!e||typeof e!=`string`||e.startsWith(`{`)||e.startsWith(`[`))return[];let r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[];let i=new Set([`total`,`.`,`..`,`...`,`.git`,`.DS_Store`,`node_modules`,`__pycache__`,`.learnings`,`dist`,`.trae`]),a=r.some(e=>/^[d-][rwx-]{9}[@+*]?$/.test(e)),o=n?[...n.matchAll(/find\b[\s\S]*?-type\s+([df])/g)].map(e=>e[1]):[],s=o.length===1?o[0]:null,c=/[<>"'`|&;()[\]*?#!]/,l=new Map,u=(e,t)=>{!e||i.has(e)||/^\d+$/.test(e)||c.test(e)||(!l.has(e)||t)&&l.set(e,t)},d=e=>e.startsWith(`/`)?Q(e):Q((t?t.replace(/\/$/,``)+`/`:``)+e),f=e=>!(e.split(`/`).pop()||``).includes(`.`);if(r.some(e=>/^\.\/([^:]+):$/.test(e)&&e.length>3)){let e=new Set;for(let t of r){let n=t.match(/^\.\/([^:]+):$/);n&&n[1]&&e.add(n[1])}let t=null;for(let n of r){let r=n.match(/^\.\/([^:]+):$/);if(r&&r[1]){t=r[1],u(t,!0);continue}if(n.startsWith(`./`)){let t=n.slice(2);t&&!i.has(t)&&u(t,e.has(t)||f(t)&&s!==`f`);continue}if(!(i.has(n)||n.startsWith(`-`)||a||n.endsWith(`...`)))if(t===null)(n.includes(`.`)||e.has(n))&&u(n,e.has(n));else{if(n.includes(`/`)){u(n,e.has(n)||f(n));continue}let r=t+`/`+n;u(r,e.has(r)||f(r))}}}else for(let e of r){if(i.has(e)||e.startsWith(`-`)||e.startsWith(`=`)||e.endsWith(`...`)||e.includes(`:`)||e.includes(`=`)||/^\d+$/.test(e)||/^[\d.]+[KMGTPE]?B?$/i.test(e))continue;let t=null;if(e.startsWith(`./`)){if(e.length<=2)continue;t=e.slice(2)}else if(a)continue;else{if(!e.includes(`/`)&&!/^.+\.[a-zA-Z0-9]+$/.test(e))continue;t=e}!t||i.has(t)||u(t,f(t)&&s!==`f`)}let p=[];for(let[e,t]of l)p.push({path:d(e),isDir:t});return p}function Ry(e){if(!e||typeof e!=`string`)return[];let t=[],n=/cat\s+>\s*['"]?(\S+)['"]?\s*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*(?=\n|$)/g,r;for(;(r=n.exec(e))!==null;){let e=r[1],n=Sy(e);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(n)&&t.push({path:Q(e),content:r[3],ext:n})}return t}function zy(e,t){if(!e||typeof e!=`string`)return null;let n=e.trim();for(let e of t){let t=xy(e).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),r=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=e.replace(/\//g,`\\`).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(RegExp(`(?:^|[;\\s&|])(?:ba)?sh\\s+.*${t}|(?:^|[;\\s&|])python[23]?\\s+.*${t}|(?:^|[;\\s&|])node\\s+.*${t}|(?:^|[;\\s&|])\\.?/${t}|(?:^|[;\\s&|])cmd(?:\\.exe)?\\s+(?:/c|/k)\\s+.*${t}|(?:^|[;\\s&|])(?:powershell|pwsh)(?:\\.exe)?\\s+(?:-[\w-]+\\s+)*-File\\s+.*${t}|(?:^|[;\\s&|])${r}|(?:^|[;\\s&|])${i}`).test(n))return e}return null}function By(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&!/^[A-Za-z]:[\\/]/.test(e)&&r&&(e=Q(r.replace(/\/$/,``)+`/`+e)),Q(e)),a=Oy(e);for(let e of a){let t=e.trim();if(!t)continue;let a=t.match(/^cd\s+(?:\/[dD]\s+)?(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||/^[A-Za-z]:/.test(e)?Q(e):e.startsWith(`~/`)?e:e===`..`?r?Q(r).replace(/\/[^/]+$/,``)||`/`:`..`:Q(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=t.match(/^rm\s+((?:-[a-zA-Z]+\s+)*)(.+)$/);if(o){let e=o[1],t=o[2],r=/r|R/i.test(e),a=Ey(wy(t,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)),i);for(let e of a)n.push({path:e,isDir:r});continue}let s=t.match(/^(?:del|erase)\s+((?:\/[a-zA-Z]+\s+)*)(.+)$/i);if(s){s[1];let e=s[2],t=Ey(wy(e,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`/`)),i);for(let e of t)n.push({path:e,isDir:!1});continue}let c=t.match(/^(?:rmdir|rd)\s+((?:\/[a-zA-Z]+\s+)*)(.+)$/i);if(c){let e=c[1],t=c[2],r=/s|S/i.test(e),a=Ey(wy(t,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`/`)),i);for(let e of a)n.push({path:e,isDir:r});continue}let l=t.match(/^Remove-Item\s+((?:-[\w-]+\s+)*(?:"[^"]+"|\S+)?(?:\s+(?:-[\w-]+\s+)*(?:"[^"]+"|\S+))*)/i);if(l){let e=l[1],t=/-Recurse/i.test(e),r=Ey([...e.matchAll(/(?:"([^"]+)"|(?<![-\/])(\S+))/g)].map(e=>e[1]||e[2]).filter(e=>e&&!e.startsWith(`-`)),i);for(let e of r)n.push({path:e,isDir:t});continue}}return n}function Vy(e){if(!Array.isArray(e)||e.length===0)return[];let t=[],n=new Set,r=[...e].sort((e,t)=>new Date(e.timestamp||0)-new Date(t.timestamp||0)),i=new Map;for(let e of r)if(!(e.nodeType!==`tool_exec`||e.status===`failed`)){if(e.action?.name===`agent_file`){let t=e.action.params;if(typeof t==`string`)try{t=JSON.parse(t)}catch{continue}if(!t||t.action!==`write`||typeof t.content!=`string`)continue;let n=Q(t.path||t.filePath||``),r=Sy(n);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(r)&&i.set(n,{content:t.content,ext:r})}else if(e.action?.name===`agent_exec`){let t=e.action.params,n=typeof t==`string`?t:t&&typeof t==`object`?t.command:null;if(typeof n==`string`)for(let e of Ry(n))i.has(e.path)||i.set(e.path,{content:e.content,ext:e.ext})}}let a=[...i.keys()],o=new Map,s=(e,t)=>!t||e==null||t.timestamp==null?!0:new Date(t.timestamp||0).getTime()>=new Date(e||0).getTime(),c=new Set,l=!1;for(let e of r){if(e.nodeType!==`tool_exec`||!e.action)continue;let r=e.action.name||``,s=e.action.params;if(s==null)continue;if(typeof s==`string`)try{s=JSON.parse(s)}catch{continue}if(typeof s!=`object`)continue;if(r===`agent_exec`){let u=s.command||``;if(!u)continue;let d=zy(u,a);if(d&&e.status!==`failed`){let a=i.get(d);if(a){let i=Iy(a.content,a.ext);for(let a of i){if(!a)continue;let i=(a.startsWith(`/`),Q(a));if(n.has(i)){let e=t.findIndex(e=>e.path===i);e>=0&&t.splice(e,1)}n.add(i),t.push({path:i,fileName:xy(i),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}}}if(e.status!==`failed`){let t=By(u,s.cwd);for(let n of t)o.set(n.path,{isDir:n.isDir,timestamp:e.timestamp})}let f=Fy(u,s.cwd);for(let e of f)if(e&&e.path){let t=e.isDir?e.path:Ay(e.path);t&&c.add(t)}for(let i of f){let a=i&&i.path;if(a){if(n.has(a)){let e=t.findIndex(e=>e.path===a);e>=0&&t.splice(e,1)}n.add(a),e.status!==`failed`&&t.push({path:a,fileName:xy(a),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:i.isDir?`directory`:`file`})}}let p=f.length>0||!!d||/<<-?/.test(u);if(e.status!==`failed`&&typeof e.observation==`string`){let i=Py(u,s.cwd);/\bcd\s/.test(u)&&i&&(p||l)&&c.add(Q(i));let a=Ly(e.observation,i,u);a.length>0&&!p&&(a=My(u)?[]:a.filter(e=>Ny(e.path,c)));for(let i of a){if(n.has(i.path)){let e=t.findIndex(e=>e.path===i.path);e>=0&&t.splice(e,1)}n.add(i.path),t.push({path:i.path,fileName:xy(i.path),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:i.isDir?`directory`:`file`})}}e.status!==`failed`&&p&&(l=!0);continue}let u=null,d=`typeOther`;if(r===`agent_file`){let t=s.action;if(t===`write`)u=s.path||s.filePath,d=`typeWrite`;else if(t===`delete`){let t=Q(s.path||s.filePath||``);t&&e.status!==`failed`&&o.set(t,{isDir:!1,timestamp:e.timestamp});continue}else continue}else if(r===`file_upload`)u=s.path||s.filePath||s.filename,d=`typeCreate`;else if(r===`download_file`)continue;else s.file_path&&(s.content!==void 0||s.action===`write`||s.action===`create`)&&(u=s.file_path,d=s.action===`create`?`typeCreate`:`typeWrite`);if(!u)continue;let f=Q(Dy(e.observation)||u);if(!f)continue;if(n.has(f)){let e=t.findIndex(e=>e.path===f);e>=0&&t.splice(e,1)}if(n.add(f),e.status===`failed`)continue;let p=Ay(f);p&&c.add(p),l=!0;let m=0;if(e.observation){let t=e.observation;if(typeof t==`string`)try{t=JSON.parse(t)}catch{}t&&typeof t==`object`&&(m=t.size||t.fileSize||t.file_size||0)}t.push({path:f,fileName:xy(f),toolName:r,action:d,size:m,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}if(o.size>0){let e=[...o.keys()],n=(e,t)=>{if(e===t)return!0;let n=e.startsWith(`/`),r=t.startsWith(`/`);return n&&!r?e.endsWith(`/`+t)||e.endsWith(t):r&&!n?t.endsWith(`/`+e)||t.endsWith(e):!1};for(let r of t)r.deleted||(o.has(r.path)&&s(r.timestamp,o.get(r.path))||e.some(e=>{let t=o.get(e);return s(r.timestamp,t)?n(r.path,e)?!0:t&&t.isDir&&(r.path.startsWith(e+`/`)||r.path.startsWith(e+`\\`)):!1}))&&(r.deleted=!0)}return t.filter(e=>e&&e.fileName)}function Hy(e){if(!e||typeof e!=`string`)return[];let t=[],n=new Set,r=/\[\[artifact:([^\]|]+)(?:\|([^\]]*))?\]\]/g,i;for(;(i=r.exec(e))!==null;){let e=(i[1]||``).trim(),r=(i[2]||``).trim();if(!e||/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z0-9_]+%/.test(e))continue;let a=Uy(e);!a||n.has(a)||(n.add(a),t.push({path:e,note:r}))}return t}function Uy(e){return Q(e).replace(/^\.\//,``)}function Wy(e,t){let n=(e||[]).map(e=>({...e,source:e.source||`static`})),r=n.map(e=>Uy(e.path));for(let e of t||[]){let t=Uy(e.path);if(!t)continue;let i=xy(e.path);if(!i)continue;let a=r.indexOf(t);if(a===-1&&(a=r.findIndex(e=>e.endsWith(`/`+t))),a!==-1){let t=n[a];t&&e.note&&!t.note&&(t.note=e.note);continue}r.push(t),n.push({path:e.path,fileName:i,toolName:`declared`,action:`typeCreate`,size:0,timestamp:null,status:`unknown`,type:`file`,source:`declared`,note:e.note||``})}return n}function Gy(e,t){return Wy(Vy(e),Hy(t))}function Ky(e){try{return It(e)}catch{return!1}}var qy=null,Jy=null,Yy=null,Xy=1;function Zy(e){if(!e)return`—`;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Qy(e){if(!Yy)return e;let t=Xy;return[...e].sort((e,n)=>{let r,i;return Yy===`name`?(r=(e.fileName||e.path||``).toLowerCase(),i=(n.fileName||n.path||``).toLowerCase()):Yy===`type`?(r=e.type||`file`,i=n.type||`file`):(r=new Date(e.timestamp||0).getTime(),i=new Date(n.timestamp||0).getTime()),r<i?-t:r>i?t:0})}function $y(e,t){let n=Vt(e.fileName,e.type),i=r(`artifacts.${e.action}`),a=Zy(e.timestamp),o=Ky(e.fileName),s=`${Cy(e.path)} · ${r(`artifacts.dblClickHint`)}`;return`
|
|
1228
1228
|
<tr class="artifacts-row" data-idx="${t}" data-path="${Cy(e.path)}" data-name="${Cy(e.fileName)}">
|
|
1229
1229
|
<td class="col-index">${t+1}</td>
|
|
@@ -1262,7 +1262,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1262
1262
|
</button>`:``}
|
|
1263
1263
|
</td>
|
|
1264
1264
|
</tr>
|
|
1265
|
-
`}function eb(e,t){e.querySelectorAll(`.artifacts-row`).forEach(e=>{let n=t[parseInt(e.dataset.idx,10)];if(!n)return;e.addEventListener(`click`,e=>{e.target.closest(`.artifact-action-btn`)||e.target.closest(`.artifact-copy-btn`)||(clearTimeout(Jy),Jy=setTimeout(()=>{Jy=null,zv().catch(()=>{}),Lv(n.path).catch(e=>{i.error(`[Artifacts] locate failed:`,e)})},250))});let a=e.querySelector(`.artifact-name`);a&&a.addEventListener(`dblclick`,e=>{e.stopPropagation(),e.preventDefault(),clearTimeout(Jy),Jy=null,Ky(n.fileName)&&Rv(n.path,n.fileName).catch(e=>{i.error(`[Artifacts] preview failed:`,e)})});let o=e.querySelector(`.artifact-copy-btn`);o&&o.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.ctrlKey||e.metaKey,i=n.fileName;t&&(i=await Vv(n.path)||n.path),
|
|
1265
|
+
`}function eb(e,t){e.querySelectorAll(`.artifacts-row`).forEach(e=>{let n=t[parseInt(e.dataset.idx,10)];if(!n)return;e.addEventListener(`click`,e=>{e.target.closest(`.artifact-action-btn`)||e.target.closest(`.artifact-copy-btn`)||(clearTimeout(Jy),Jy=setTimeout(()=>{Jy=null,zv().catch(()=>{}),Lv(n.path).catch(e=>{i.error(`[Artifacts] locate failed:`,e)})},250))});let a=e.querySelector(`.artifact-name`);a&&a.addEventListener(`dblclick`,e=>{e.stopPropagation(),e.preventDefault(),clearTimeout(Jy),Jy=null,Ky(n.fileName)&&Rv(n.path,n.fileName).catch(e=>{i.error(`[Artifacts] preview failed:`,e)})});let o=e.querySelector(`.artifact-copy-btn`);o&&o.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.ctrlKey||e.metaKey,i=n.fileName;t&&(i=await Vv(n.path)||n.path),Ve(i,o),P(t?r(`artifacts.copiedPath`):r(`artifacts.copiedName`,{name:n.fileName}),`success`)});let s=e.querySelector(`.download-btn`);s&&s.addEventListener(`click`,e=>{e.stopPropagation(),nb(n)}),e.querySelectorAll(`.locate-btn, .preview-btn`).forEach(e=>{e.addEventListener(`click`,async t=>{if(t.stopPropagation(),e.classList.contains(`locate-btn`)){zv().catch(()=>{});try{await Lv(n.path)}catch(e){i.error(`[Artifacts] locate failed:`,e)}}else if(e.classList.contains(`preview-btn`))try{await Rv(n.path,n.fileName)}catch(e){i.error(`[Artifacts] preview failed:`,e)}})})})}function tb(e,t){let n=Qy(t),r=e.querySelector(`.artifacts-table tbody`);r.innerHTML=n.map((e,t)=>$y(e,t)).join(``),e.querySelectorAll(`.artifacts-table th.sortable`).forEach(e=>{let t=e.dataset.sort;e.classList.toggle(`sorted-asc`,t===Yy&&Xy===1),e.classList.toggle(`sorted-desc`,t===Yy&&Xy===-1)}),eb(e,n)}async function nb(e){let t=null;try{t=e.type===`directory`?await Ut([e.path]):await Ot(e.path)}catch(e){t={success:!1,error:e.message}}if(!t||!t.success){let e=t&&t.error?`: ${t.error}`:``;P(r(`artifacts.downloadFailed`)+e,`error`);return}let n=URL.createObjectURL(t.blob),i=document.createElement(`a`),a=t.name||xy(e.path)||`workspace.zip`;if(e.type===`directory`){let t=xy(e.path);t&&(a=t.replace(/\.zip$/i,``)+`.zip`)}i.href=n,i.download=a,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(n),5e3)}function rb(e,t){if(!t)return!0;let n=Q(e||``);if(!n||n.startsWith(`~/`)||n===`~`)return!1;if(!(n.startsWith(`/`)||/^[a-zA-Z]:\//.test(n)))return!0;let r=n.toLowerCase(),i=t.toLowerCase();return r===i||r.startsWith(i+`/`)}function ib(e,t){return!t||!(e===`~`||e&&e.startsWith(`~/`))?e:Q(e===`~`?t:t+`/`+e.slice(2))}function ab(e,t){let n=e.querySelector(`.artifacts-modal-count`);n&&(n.textContent=r(`artifacts.totalCount`,{count:t.length}))}async function ob(e){if(!e||e.length===0)return!1;let t=null;try{let e=await Kt();e&&(t=Q(e))}catch{}let n=null;try{n=await Pt()}catch{}let r=!1;if(t)for(let i=e.length-1;i>=0;i--){let a=e[i];rb(ib(a.path,n),t)||(e.splice(i,1),r=!0)}if(e.length===0)return r;try{let t=new Map;await Promise.all(e.map(async e=>{let n=e.path;try{let t=await Vv(e.path);t&&(n=t)}catch{}t.has(n)||t.set(n,[]),t.get(n).push(e.path)}));let n=[...t.keys()];if(n.length===0)return r;let i=await chrome.runtime.sendMessage({type:`CHECK_FILES_EXIST`,paths:n});if(!i||!i.success||!i.results)return r;let a=new Set;for(let[e,n]of t)if(i.results[e]===!1)for(let e of n)a.add(e);if(a.size>0)for(let t=e.length-1;t>=0;t--)a.has(e[t].path)&&(e.splice(t,1),r=!0)}catch{}return r}function sb(e,t){if(!e)return;let n=e.querySelector(`.artifacts-btn-count`);t>0?(n&&(n.textContent=t),e.title=r(`artifacts.btnTitle`,{count:t}),e.style.display=``):e.style.display=`none`}function cb(e,t){!e||e.length===0||!t||ob(e).then(n=>{n&&sb(t,e.length)}).catch(()=>{})}function lb(e){if(!e)return 0;for(let t=e.length-1;t>=0;t--)e[t].deleted&&e.splice(t,1);return e.length}function ub(e,t){if(db(),!e)return;for(let t=e.length-1;t>=0;t--)e[t].deleted&&e.splice(t,1);if(e.length===0){sb(t,0);return}Yy=null,Xy=1,qy=document.createElement(`div`),qy.className=`artifacts-modal-overlay`,qy.id=`artifactsModalOverlay`;let n=document.createElement(`div`);n.className=`artifacts-modal`;let i=document.createElement(`div`);i.className=`artifacts-modal-header`,i.innerHTML=`
|
|
1266
1266
|
<div class="artifacts-modal-title">
|
|
1267
1267
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:18px;height:18px;color:var(--info-500);">
|
|
1268
1268
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
@@ -1285,51 +1285,51 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1285
1285
|
</tr>
|
|
1286
1286
|
</thead>
|
|
1287
1287
|
<tbody></tbody>
|
|
1288
|
-
`,a.appendChild(o);let s=document.createElement(`div`);s.className=`artifacts-modal-footer`;let c=document.createElement(`button`);c.className=`artifacts-modal-close-btn`,c.textContent=r(`artifacts.closeBtn`),c.addEventListener(`click`,db),s.appendChild(c),n.appendChild(i),n.appendChild(a),n.appendChild(s),qy.appendChild(n);let l=document.body,u=document.getElementById(`workspacePanelContainer`);if(u&&u.classList.contains(`embedded`)){let e=document.getElementById(`mainLeft`);e&&(qy.classList.add(`embedded-mode`),e.style.position=`relative`,l=e)}l.appendChild(qy),document.getElementById(`artifactsModalClose`).addEventListener(`click`,db);let d=e=>{e.key===`Escape`&&(db(),document.removeEventListener(`keydown`,d))};document.addEventListener(`keydown`,d),o.querySelectorAll(`th.sortable`).forEach(t=>{t.addEventListener(`click`,()=>{let r=t.dataset.sort;Yy===r?Xy=-Xy:(Yy=r,Xy=1),tb(n,e)})}),tb(n,e),ob(e).then(i=>{if(!(!i||!qy)){if(e.length===0){let t=n.querySelector(`.artifacts-table tbody`);t&&(t.innerHTML=`<tr><td colspan="5" class="artifacts-empty">${r(`artifacts.emptyHint`)}</td></tr>`),ab(n,e)}else ab(n,e),tb(n,e);sb(t,e.length)}}).catch(()=>{})}function db(){Jy&&=(clearTimeout(Jy),null),qy&&=(qy.remove(),null)}n(`zh`,{promptSelector:{noMatchAgent:`没有匹配的 Agent`,inheritGlobal:`继承全局设置`,editAgentTitle:`编辑此 Agent`,deleteAgentTitle:`删除此 Agent`,noMatchProxy:`没有匹配的代理`,unnamedProxy:`未命名代理`,enableTitle:`启用此代理`,disableTitle:`禁用此代理`,noMatchAll:`没有匹配的 Agent、网页或代理`,noTitle:`无标题`,proxyAddress:`代理地址`,deleteProxyTitle:`删除此代理`,confirmDeleteProxy:`确定要删除此代理吗?`},knowledgeSelector:{disabled:`知识库检索已关闭(可在设置页「知识库」中开启)`,notAvailable:`知识库不可用(请确认代理已连接、检索依赖已安装)`,noCollections:`暂无知识库(可在设置页「知识库」中创建)`,docChunk:`{docs} 文档 · {chunks} 分块`,disabledBadge:`已停用`,disabledTooltip:`已停用(大模型不会自主检索该库),仍可手动 @ 引用`,manualSuffix:`手动引用`}}),n(`en`,{promptSelector:{noMatchAgent:`No matching agent`,inheritGlobal:`Inherit global settings`,editAgentTitle:`Edit this agent`,deleteAgentTitle:`Delete this agent`,noMatchProxy:`No matching proxy`,unnamedProxy:`Unnamed proxy`,enableTitle:`Enable this proxy`,disableTitle:`Disable this proxy`,noMatchAll:`No matching agent, page or proxy`,noTitle:`Untitled`,proxyAddress:`Proxy address`,deleteProxyTitle:`Delete this proxy`,confirmDeleteProxy:`Are you sure you want to delete this proxy?`},knowledgeSelector:{disabled:`Knowledge retrieval is turned off (you can enable it in Settings - Knowledge)`,notAvailable:`Knowledge base unavailable (check the agent connection and installed retrieval dependencies)`,noCollections:`No knowledge base yet (create one in Settings - Knowledge)`,docChunk:`{docs} docs · {chunks} chunks`,disabledBadge:`Disabled`,disabledTooltip:`Disabled (the model won't search this knowledge base autonomously); you can still reference it manually via @`,manualSuffix:`manual`}});var fb=`pages`;async function pb(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]);return(e.pairedAgents||[]).map(t=>({...t,isActive:t.id===e.activeAgentId,isDisabled:!!t.disabled}))}catch{return[]}}var mb=!1;async function hb(e=``,t=null){let n=document.getElementById(`agentAtSelector`),r=document.getElementById(`agentAtDropdown`);
|
|
1288
|
+
`,a.appendChild(o);let s=document.createElement(`div`);s.className=`artifacts-modal-footer`;let c=document.createElement(`button`);c.className=`artifacts-modal-close-btn`,c.textContent=r(`artifacts.closeBtn`),c.addEventListener(`click`,db),s.appendChild(c),n.appendChild(i),n.appendChild(a),n.appendChild(s),qy.appendChild(n);let l=document.body,u=document.getElementById(`workspacePanelContainer`);if(u&&u.classList.contains(`embedded`)){let e=document.getElementById(`mainLeft`);e&&(qy.classList.add(`embedded-mode`),e.style.position=`relative`,l=e)}l.appendChild(qy),document.getElementById(`artifactsModalClose`).addEventListener(`click`,db);let d=e=>{e.key===`Escape`&&(db(),document.removeEventListener(`keydown`,d))};document.addEventListener(`keydown`,d),o.querySelectorAll(`th.sortable`).forEach(t=>{t.addEventListener(`click`,()=>{let r=t.dataset.sort;Yy===r?Xy=-Xy:(Yy=r,Xy=1),tb(n,e)})}),tb(n,e),ob(e).then(i=>{if(!(!i||!qy)){if(e.length===0){let t=n.querySelector(`.artifacts-table tbody`);t&&(t.innerHTML=`<tr><td colspan="5" class="artifacts-empty">${r(`artifacts.emptyHint`)}</td></tr>`),ab(n,e)}else ab(n,e),tb(n,e);sb(t,e.length)}}).catch(()=>{})}function db(){Jy&&=(clearTimeout(Jy),null),qy&&=(qy.remove(),null)}n(`zh`,{promptSelector:{noMatchAgent:`没有匹配的 Agent`,inheritGlobal:`继承全局设置`,editAgentTitle:`编辑此 Agent`,deleteAgentTitle:`删除此 Agent`,noMatchProxy:`没有匹配的代理`,unnamedProxy:`未命名代理`,enableTitle:`启用此代理`,disableTitle:`禁用此代理`,noMatchAll:`没有匹配的 Agent、网页或代理`,noTitle:`无标题`,proxyAddress:`代理地址`,deleteProxyTitle:`删除此代理`,confirmDeleteProxy:`确定要删除此代理吗?`},knowledgeSelector:{disabled:`知识库检索已关闭(可在设置页「知识库」中开启)`,notAvailable:`知识库不可用(请确认代理已连接、检索依赖已安装)`,noCollections:`暂无知识库(可在设置页「知识库」中创建)`,docChunk:`{docs} 文档 · {chunks} 分块`,disabledBadge:`已停用`,disabledTooltip:`已停用(大模型不会自主检索该库),仍可手动 @ 引用`,manualSuffix:`手动引用`}}),n(`en`,{promptSelector:{noMatchAgent:`No matching agent`,inheritGlobal:`Inherit global settings`,editAgentTitle:`Edit this agent`,deleteAgentTitle:`Delete this agent`,noMatchProxy:`No matching proxy`,unnamedProxy:`Unnamed proxy`,enableTitle:`Enable this proxy`,disableTitle:`Disable this proxy`,noMatchAll:`No matching agent, page or proxy`,noTitle:`Untitled`,proxyAddress:`Proxy address`,deleteProxyTitle:`Delete this proxy`,confirmDeleteProxy:`Are you sure you want to delete this proxy?`},knowledgeSelector:{disabled:`Knowledge retrieval is turned off (you can enable it in Settings - Knowledge)`,notAvailable:`Knowledge base unavailable (check the agent connection and installed retrieval dependencies)`,noCollections:`No knowledge base yet (create one in Settings - Knowledge)`,docChunk:`{docs} docs · {chunks} chunks`,disabledBadge:`Disabled`,disabledTooltip:`Disabled (the model won't search this knowledge base autonomously); you can still reference it manually via @`,manualSuffix:`manual`}});var fb=`pages`;async function pb(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]);return(e.pairedAgents||[]).map(t=>({...t,isActive:t.id===e.activeAgentId,isDisabled:!!t.disabled}))}catch{return[]}}var mb=!1;async function hb(e=``,t=null){let n=document.getElementById(`agentAtSelector`),r=document.getElementById(`agentAtDropdown`);qe(),n.style.display=`block`,r.classList.add(`show`),vb(),t?await yb(t):await bb(e),gb()}async function gb(){try{let[e,t,n,i]=await Promise.all([gt(),Qb(),pb(),Kb()]),a=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="agents"]`),o=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="pages"]`),s=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="proxies"]`),c=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="knowledge"]`);a&&(a.textContent=r(`promptSelector.agentsCount`,{count:e.length})),o&&(o.textContent=r(`promptSelector.pagesCount`,{count:t.length})),s&&(s.textContent=r(`promptSelector.proxiesCount`,{count:n.length}),s.style.display=n.length>0?``:`none`),c&&(c.textContent=r(`promptSelector.knowledgeCount`,{count:i.collections.length}),c.style.display=i.ok?``:`none`,!i.ok&&fb===`knowledge`&&yb(`pages`))}catch{}}function _b(){let e=document.getElementById(`agentAtSelector`),t=document.getElementById(`agentAtDropdown`);e.style.display=`none`,t.classList.remove(`show`),C.selectedAgentAtIndex=-1,C.selectedPageIndex=-1,C.selectedProxyAtIndex=-1,C.selectedKnowledgeAtIndex=-1}function vb(){let e=document.getElementById(`agentAtDropdown`);if(!e||e.dataset.initialized)return;e.dataset.initialized=`1`,e.addEventListener(`mousedown`,e=>{e.target.closest(`.prompt-item, .prompt-tab, .skill-list-item, .mcp-list-item`)&&e.preventDefault()});let t=document.getElementById(`agentAtTabs`);t&&t.querySelectorAll(`.prompt-tab`).forEach(e=>{e.addEventListener(`click`,()=>{yb(e.dataset.tab)})}),e.addEventListener(`click`,async e=>{if(e.target.closest(`#agentAddBtn`)){e.stopPropagation(),_b(),mE(null);return}if(e.target.closest(`#proxyAddBtn`)){e.stopPropagation(),_b(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`agent`});return}if(e.target.closest(`#knowledgeAddBtn`)){e.stopPropagation(),_b(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`knowledge`});return}if(e.target.closest(`#pageAddBtn`)){e.stopPropagation(),_b(),chrome.tabs.create({});return}let t=e.target.closest(`.agent-edit-btn`);if(t){e.stopPropagation();let n=t.dataset.agentId;_b(),mE(n);return}let n=e.target.closest(`.agent-delete-btn`);if(n){e.stopPropagation();let t=n.dataset.agentId;if(await PE(t)){let e=document.getElementById(`userInput`);await bb(e?xb(e.value):``)}}})}async function yb(e){fb=e;let t=document.getElementById(`agentAtTabs`);t&&t.querySelectorAll(`.prompt-tab`).forEach(t=>{t.classList.toggle(`active`,t.dataset.tab===e)});let n=document.getElementById(`agentAtList`),r=document.getElementById(`agentPageList`),i=document.getElementById(`agentProxyList`),a=document.getElementById(`agentKnowledgeList`);n&&(n.style.display=e===`agents`?``:`none`),r&&(r.style.display=e===`pages`?``:`none`),i&&(i.style.display=e===`proxies`?``:`none`),a&&(a.style.display=e===`knowledge`?``:`none`);let o=document.getElementById(`agentAtDropdown`);o&&o.setAttribute(`data-active-tab`,e);let s=document.getElementById(`userInput`);s&&s.focus(),await bb(s?xb(s.value):``)}async function bb(e=``){let t=document.getElementById(`agentAtTabs`),n=document.getElementById(`agentPageList`),r=document.getElementById(`agentAtList`),i=document.getElementById(`agentProxyList`),a=document.getElementById(`agentKnowledgeList`);if(e){mb=!0,t&&t.classList.add(`merged-mode`),n&&(n.style.display=`none`),i&&(i.style.display=`none`),a&&(a.style.display=`none`),r&&(r.style.display=``),await Mb(e);let o=document.getElementById(`agentAtDropdown`);o&&o.setAttribute(`data-active-tab`,`merged`)}else{mb=!1,t&&t.classList.remove(`merged-mode`),t&&t.querySelectorAll(`.prompt-tab`).forEach(e=>{e.classList.toggle(`active`,e.dataset.tab===fb)}),n&&(n.style.display=fb===`pages`?``:`none`),r&&(r.style.display=fb===`agents`?``:`none`),i&&(i.style.display=fb===`proxies`?``:`none`),a&&(a.style.display=fb===`knowledge`?``:`none`);let e=document.getElementById(`agentAtDropdown`);e&&e.setAttribute(`data-active-tab`,fb),fb===`pages`?await $b(``):fb===`proxies`?await jb(``):fb===`knowledge`?await qb(``):await wb(``)}}function xb(e){let t=e.lastIndexOf(`@`);return t===-1?``:e.substring(t+1)}function Sb(e){return e.id==="default"?r(`agentMgr.defaultAgentName`):e.name}function Cb(e){return e.id==="default"?r(`agentMgr.defaultAgentDesc`):e.description}async function wb(e=``){let t=document.getElementById(`agentAtList`);if(!t)return;let n=await gt(),i=(e||``).toLowerCase(),a=n.filter(t=>{if(!e)return!0;let n=Sb(t),r=Cb(t);return n&&n.toLowerCase().includes(i)||r&&r.toLowerCase().includes(i)});if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchAgent`)}</div>`,C.selectedAgentAtIndex=-1;return}C.selectedAgentAtIndex=0,t.innerHTML=a.map((e,t)=>{let n=e.id===C.activeAgentId||!C.activeAgentId&&e.id==="default",i=e.toolIds?e.toolIds.length:e.toolIds===null?null:0,a=i===null?r(`promptSelector.inheritGlobal`):r(`promptSelector.toolCount`,{count:i}),o=Sb(e),s=Cb(e);return`
|
|
1289
1289
|
<div class="prompt-item ${t===0?`selected`:``} ${n?`agent-at-active`:``}"
|
|
1290
|
-
data-index="${t}" data-agent-id="${
|
|
1290
|
+
data-index="${t}" data-agent-id="${I(e.id)}">
|
|
1291
1291
|
<span class="prompt-item-index">${t+1}</span>
|
|
1292
|
-
<span class="agent-at-icon">${
|
|
1293
|
-
<span class="prompt-item-content">${
|
|
1294
|
-
<span class="prompt-item-code">${
|
|
1292
|
+
<span class="agent-at-icon">${I(e.icon)}</span>
|
|
1293
|
+
<span class="prompt-item-content">${I(o)}</span>
|
|
1294
|
+
<span class="prompt-item-code">${I(s||a)}</span>
|
|
1295
1295
|
<span class="agent-item-actions">
|
|
1296
1296
|
<span class="agent-active-mark" style="${n?``:`display:none`}">✓</span>
|
|
1297
|
-
<span class="agent-edit-btn" data-agent-id="${
|
|
1298
|
-
${e.isBuiltin?``:`<span class="agent-delete-btn" data-agent-id="${
|
|
1297
|
+
<span class="agent-edit-btn" data-agent-id="${I(e.id)}" title="${r(`promptSelector.editAgentTitle`)}">✎</span>
|
|
1298
|
+
${e.isBuiltin?``:`<span class="agent-delete-btn" data-agent-id="${I(e.id)}" title="${r(`promptSelector.deleteAgentTitle`)}">✕</span>`}
|
|
1299
1299
|
</span>
|
|
1300
1300
|
</div>
|
|
1301
1301
|
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{t.target.closest(`.agent-edit-btn`)||t.target.closest(`.agent-delete-btn`)||await Ib(e.dataset.agentId)})})}async function Tb(e){if(!e?.url)return{online:!1};try{let t=new AbortController;setTimeout(()=>t.abort(),2e3);let n=await fetch(`${e.url}/api/status`,{signal:t.signal});if(!n.ok)return{online:!1};let r=await n.json();return{online:!0,version:r.version||null,platformName:r.platformName||r.platform||null,arch:r.arch||null}}catch{return{online:!1}}}var Eb=new Map,Db=1e4;function Ob(e){let t=Eb.get(e.id);return t&&Date.now()-t.ts<Db?t:null}function kb(e,t){return e.isDisabled?`disabled`:e.isActive?t?`connected`:`disconnected`:t?`online`:`offline`}async function Ab(e){if(Ob(e))return;let t=await Tb(e);Eb.set(e.id,{online:t.online,version:t.version||null,platformName:t.platformName||null,ts:Date.now()}),document.querySelectorAll(`.prompt-item-proxy`).forEach(n=>{if(n.dataset.proxyId===e.id){let r=n.querySelector(`.agent-at-dot`);r&&(r.className=`agent-at-dot agent-at-dot-${kb(e,t.online)}`)}})}async function jb(e=``){let t=document.getElementById(`agentProxyList`);if(!t)return;let n=await pb(),i=(e||``).toLowerCase(),a=n.filter(t=>e?t.name.toLowerCase().includes(i)||t.url&&t.url.toLowerCase().includes(i):!0);if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchProxy`)}</div>`,C.selectedProxyAtIndex=-1;return}C.selectedProxyAtIndex=0,t.innerHTML=a.map((e,t)=>{let n=Ob(e),i=e.isActive,a=e.isDisabled,o=kb(e,n?n.online:!1),s=e.name||r(`promptSelector.unnamedProxy`);return`
|
|
1302
1302
|
<div class="prompt-item ${t===0?`selected`:``} ${i?`agent-at-active`:``} ${a?`agent-disabled`:``} prompt-item-proxy"
|
|
1303
|
-
data-index="${t}" data-proxy-id="${
|
|
1303
|
+
data-index="${t}" data-proxy-id="${I(e.id)}">
|
|
1304
1304
|
<span class="prompt-item-index">${t+1}</span>
|
|
1305
1305
|
<span class="agent-at-dot agent-at-dot-${o}"></span>
|
|
1306
|
-
<span class="prompt-item-content">${
|
|
1307
|
-
<span class="prompt-item-code" title="${
|
|
1306
|
+
<span class="prompt-item-content">${I(s)}</span>
|
|
1307
|
+
<span class="prompt-item-code" title="${I(e.url||``)}">${I(e.url||``)}</span>
|
|
1308
1308
|
<span class="agent-item-actions">
|
|
1309
1309
|
${i?`<span class="agent-active-mark">✓</span>`:``}
|
|
1310
1310
|
</span>
|
|
1311
|
-
${a?`<span class="proxy-enable-btn" data-action="enable" data-id="${
|
|
1312
|
-
<span class="proxy-delete-btn" data-action="delete" data-id="${
|
|
1311
|
+
${a?`<span class="proxy-enable-btn" data-action="enable" data-id="${I(e.id)}" title="${r(`promptSelector.enableTitle`)}">▶</span>`:`<span class="proxy-disable-btn" data-action="disable" data-id="${I(e.id)}" title="${r(`promptSelector.disableTitle`)}">⏸</span>`}
|
|
1312
|
+
<span class="proxy-delete-btn" data-action="delete" data-id="${I(e.id)}" title="${r(`common.delete`)}">✕</span>
|
|
1313
1313
|
</div>
|
|
1314
1314
|
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.proxy-disable-btn, .proxy-delete-btn, .proxy-enable-btn`);if(n){t.stopPropagation(),await Zb(n.dataset.action,n.dataset.id);return}await Jb(e.dataset.proxyId)})}),a.forEach(e=>Ab(e))}async function Mb(e=``){let t=document.getElementById(`agentAtList`);if(!t)return;let n=e.toLowerCase(),[i,a,o,s]=await Promise.all([gt(),Qb(),pb(),Kb()]),c=i.filter(e=>{let t=Sb(e),r=Cb(e);return t&&t.toLowerCase().includes(n)||r&&r.toLowerCase().includes(n)}),l=a.filter(e=>{if(!e.url)return!1;let t=(e.title||``).toLowerCase().includes(n),r=e.url.toLowerCase().includes(n);return t||r}),u=o.filter(e=>e.name.toLowerCase().includes(n)||e.url&&e.url.toLowerCase().includes(n)),d=s.ok?s.collections.filter(e=>e.name&&e.name.toLowerCase().includes(n)||e.description&&e.description.toLowerCase().includes(n)):[],f=c.length+l.length+u.length+d.length,p=document.getElementById(`agentAtMergedTitle`);if(p&&(p.textContent=r(`promptSelector.mergedTitleCount`,{count:f})),f===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchAll`)}</div>`,C.selectedAgentAtIndex=-1;return}C.selectedAgentAtIndex=0;let m=``,h=0;c.forEach(e=>{let t=e.id===C.activeAgentId||!C.activeAgentId&&e.id==="default",n=e.toolIds?e.toolIds.length:e.toolIds===null?null:0,i=n===null?r(`promptSelector.inheritGlobal`):r(`promptSelector.toolCount`,{count:n}),a=Sb(e),o=Cb(e);m+=`
|
|
1315
1315
|
<div class="prompt-item${h===0?` selected`:``}${t?` agent-at-active`:``}"
|
|
1316
|
-
data-index="${h}" data-type="agent" data-agent-id="${
|
|
1316
|
+
data-index="${h}" data-type="agent" data-agent-id="${I(e.id)}">
|
|
1317
1317
|
<span class="prompt-item-index">${h+1}</span>
|
|
1318
|
-
<span class="agent-at-icon">${
|
|
1319
|
-
<span class="prompt-item-content">${
|
|
1320
|
-
<span class="prompt-item-code">${
|
|
1318
|
+
<span class="agent-at-icon">${I(e.icon)}</span>
|
|
1319
|
+
<span class="prompt-item-content">${I(a)}</span>
|
|
1320
|
+
<span class="prompt-item-code">${I(o||i)}</span>
|
|
1321
1321
|
<span class="agent-item-actions">
|
|
1322
1322
|
<span class="agent-active-mark" style="${t?``:`display:none`}">✓</span>
|
|
1323
|
-
<span class="agent-edit-btn" data-agent-id="${
|
|
1324
|
-
${e.isBuiltin?``:`<span class="agent-delete-btn" data-agent-id="${
|
|
1323
|
+
<span class="agent-edit-btn" data-agent-id="${I(e.id)}" title="${r(`promptSelector.editAgentTitle`)}">✎</span>
|
|
1324
|
+
${e.isBuiltin?``:`<span class="agent-delete-btn" data-agent-id="${I(e.id)}" title="${r(`promptSelector.deleteAgentTitle`)}">✕</span>`}
|
|
1325
1325
|
</span>
|
|
1326
|
-
</div>`,h++});let g=C.selectedPage?C.selectedPage.id:null;l.forEach(e=>{let t=e.title||r(`promptSelector.noTitle`),n=e.url||``,i=e.favIconUrl?`<img src="${
|
|
1326
|
+
</div>`,h++});let g=C.selectedPage?C.selectedPage.id:null;l.forEach(e=>{let t=e.title||r(`promptSelector.noTitle`),n=e.url||``,i=e.favIconUrl?`<img src="${I(e.favIconUrl)}" width="16" height="16" style="flex-shrink:0;" class="favicon-img">`:`<span style="font-size:14px;flex-shrink:0;">🌐</span>`,a=e.id===g;m+=`
|
|
1327
1327
|
<div class="prompt-item${h===0?` selected`:``} prompt-item-page"
|
|
1328
1328
|
data-index="${h}" data-type="page" data-tab-id="${e.id}">
|
|
1329
1329
|
<span class="prompt-item-index">${h+1}</span>
|
|
1330
1330
|
${i}
|
|
1331
|
-
<span class="prompt-item-content" title="${
|
|
1332
|
-
<span class="prompt-item-code" title="${
|
|
1331
|
+
<span class="prompt-item-content" title="${I(t)}">${I(t)}</span>
|
|
1332
|
+
<span class="prompt-item-code" title="${I(n)}">${I(n)}</span>
|
|
1333
1333
|
${a?`<span class="page-item-actions"><span class="page-selected-mark">✓</span></span>`:``}
|
|
1334
1334
|
<span class="page-action-toolbar">
|
|
1335
1335
|
<span class="page-action-btn" data-action="interpret" data-tab-id="${e.id}" title="${r(`pageSelector.interpretPage`)}">${r(`pageSelector.interpretPage`)}</span>
|
|
@@ -1338,46 +1338,46 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1338
1338
|
</span>
|
|
1339
1339
|
</div>`,h++}),d.forEach(e=>{let t=C.knowledgeRefs.some(t=>t.id===e.id),n=r(`knowledgeSelector.docChunk`,{docs:e.documentCount||0,chunks:e.chunkCount||0}),i=e.enabled===!1;m+=`
|
|
1340
1340
|
<div class="prompt-item${h===0?` selected`:``}${t?` agent-at-active picked`:``}${i?` knowledge-item-disabled`:``} prompt-item-knowledge"
|
|
1341
|
-
data-index="${h}" data-type="knowledge" data-kb-id="${
|
|
1342
|
-
data-kb-disabled="${i?`1`:`0`}"${i?` title="${
|
|
1341
|
+
data-index="${h}" data-type="knowledge" data-kb-id="${I(e.id)}" data-kb-name="${I(e.name||``)}"
|
|
1342
|
+
data-kb-disabled="${i?`1`:`0`}"${i?` title="${I(r(`knowledgeSelector.disabledTooltip`))}"`:``}>
|
|
1343
1343
|
<span class="prompt-item-index">${h+1}</span>
|
|
1344
1344
|
<span class="agent-at-icon">📚</span>
|
|
1345
|
-
<span class="prompt-item-content">${
|
|
1345
|
+
<span class="prompt-item-content">${I(e.name||``)}</span>
|
|
1346
1346
|
${i?`<span class="knowledge-item-badge badge-disabled">${r(`knowledgeSelector.disabledBadge`)}</span>`:``}
|
|
1347
|
-
<span class="prompt-item-code">${
|
|
1347
|
+
<span class="prompt-item-code">${I(n)}</span>
|
|
1348
1348
|
</div>`,h++}),u.forEach(e=>{let t=e.isActive,n=e.isDisabled,i=Ob(e),a=kb(e,i?i.online:!1),o=e.name||r(`promptSelector.unnamedProxy`);m+=`
|
|
1349
1349
|
<div class="prompt-item${h===0?` selected`:``}${t?` agent-at-active`:``}${n?` agent-disabled`:``} prompt-item-proxy"
|
|
1350
|
-
data-index="${h}" data-type="proxy" data-proxy-id="${
|
|
1350
|
+
data-index="${h}" data-type="proxy" data-proxy-id="${I(e.id)}">
|
|
1351
1351
|
<span class="prompt-item-index">${h+1}</span>
|
|
1352
1352
|
<span class="agent-at-dot agent-at-dot-${a}"></span>
|
|
1353
|
-
<span class="prompt-item-content">${
|
|
1354
|
-
<span class="prompt-item-code" title="${
|
|
1353
|
+
<span class="prompt-item-content">${I(o)}</span>
|
|
1354
|
+
<span class="prompt-item-code" title="${I(e.url||``)}">${I(e.url||``)}</span>
|
|
1355
1355
|
${t?`<span class="agent-item-actions"><span class="agent-active-mark">✓</span></span>`:``}
|
|
1356
|
-
${n?`<span class="proxy-enable-btn" data-action="enable" data-id="${
|
|
1357
|
-
<span class="proxy-delete-btn" data-action="delete" data-id="${
|
|
1358
|
-
</div>`,h++}),t.innerHTML=m,t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),u.forEach(e=>Ab(e)),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),ix(parseInt(n.dataset.tabId),n.dataset.action);return}let r=t.target.closest(`.proxy-disable-btn, .proxy-delete-btn, .proxy-enable-btn`);if(r){t.stopPropagation(),await Zb(r.dataset.action,r.dataset.id);return}if(t.target.closest(`.agent-edit-btn`)||t.target.closest(`.agent-delete-btn`))return;let i=e.dataset.type;i===`agent`?await Ib(e.dataset.agentId):i===`page`?Lb(parseInt(e.dataset.tabId)):i===`knowledge`?(zb({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&_b()):i===`proxy`&&await Jb(e.dataset.proxyId)})})}function Nb(e){let t;t=mb?C.selectedAgentAtIndex:fb===`proxies`?C.selectedProxyAtIndex:fb===`knowledge`?C.selectedKnowledgeAtIndex:C.selectedAgentAtIndex,e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function Pb(){let e=document.getElementById(`userInput`);if(!e)return;let t=e.value,n=t.lastIndexOf(`@`);n!==-1&&(e.value=t.substring(0,n)),e.focus(),e.selectionStart=e.selectionEnd=e.value.length}function Fb(){let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}async function Ib(e,{clearTrigger:t=!0}={}){t?Pb():Fb(),_b(),await eE(e),
|
|
1356
|
+
${n?`<span class="proxy-enable-btn" data-action="enable" data-id="${I(e.id)}" title="${r(`promptSelector.enableTitle`)}">▶</span>`:`<span class="proxy-disable-btn" data-action="disable" data-id="${I(e.id)}" title="${r(`promptSelector.disableTitle`)}">⏸</span>`}
|
|
1357
|
+
<span class="proxy-delete-btn" data-action="delete" data-id="${I(e.id)}" title="${r(`common.delete`)}">✕</span>
|
|
1358
|
+
</div>`,h++}),t.innerHTML=m,t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),u.forEach(e=>Ab(e)),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),ix(parseInt(n.dataset.tabId),n.dataset.action);return}let r=t.target.closest(`.proxy-disable-btn, .proxy-delete-btn, .proxy-enable-btn`);if(r){t.stopPropagation(),await Zb(r.dataset.action,r.dataset.id);return}if(t.target.closest(`.agent-edit-btn`)||t.target.closest(`.agent-delete-btn`))return;let i=e.dataset.type;i===`agent`?await Ib(e.dataset.agentId):i===`page`?Lb(parseInt(e.dataset.tabId)):i===`knowledge`?(zb({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&_b()):i===`proxy`&&await Jb(e.dataset.proxyId)})})}function Nb(e){let t;t=mb?C.selectedAgentAtIndex:fb===`proxies`?C.selectedProxyAtIndex:fb===`knowledge`?C.selectedKnowledgeAtIndex:C.selectedAgentAtIndex,e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function Pb(){let e=document.getElementById(`userInput`);if(!e)return;let t=e.value,n=t.lastIndexOf(`@`);n!==-1&&(e.value=t.substring(0,n)),e.focus(),e.selectionStart=e.selectionEnd=e.value.length}function Fb(){let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}async function Ib(e,{clearTrigger:t=!0}={}){t?Pb():Fb(),_b(),await eE(e),lt()}function Lb(e){Pb(),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[AgentAtSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}tx(e),_b();let t=document.getElementById(`userInput`);t&&(t.focus(),lt())})}function Rb(){let e=new Set(C.knowledgeRefs.map(e=>e.id));document.querySelectorAll(`.prompt-item-knowledge`).forEach(t=>{let n=e.has(t.dataset.kbId);t.classList.toggle(`agent-at-active`,n),t.classList.toggle(`picked`,n)})}function zb(e,{clearTrigger:t=!0}={}){t?Pb():Fb();let n=C.knowledgeRefs.findIndex(t=>t.id===e.id);n>=0?C.knowledgeRefs.splice(n,1):C.knowledgeRefs.push({id:e.id,name:e.name||e.id,enabled:e.enabled!==!1}),Rb(),Hb(),lt()}function Bb(e){C.knowledgeRefs=C.knowledgeRefs.filter(t=>t.id!==e),Rb(),Hb()}function Vb(){C.knowledgeRefs=[],Rb(),Hb()}function Hb(){let e=document.getElementById(`knowledgeIndicator`);if(e){if(C.knowledgeRefs.length===0){e.style.display=`none`,e.innerHTML=``;return}e.innerHTML=C.knowledgeRefs.map(e=>{let t=e.enabled===!1,n=t?`${e.name} (${r(`knowledgeSelector.manualSuffix`)})`:e.name;return`
|
|
1359
1359
|
<span class="knowledge-chip${t?` knowledge-chip-manual`:``}">
|
|
1360
|
-
<span class="knowledge-chip-name" title="${
|
|
1361
|
-
<button class="knowledge-chip-close" data-kb-id="${
|
|
1360
|
+
<span class="knowledge-chip-name" title="${I(t?r(`knowledgeSelector.disabledTooltip`):e.name)}">📚 ${I(n)}</span>
|
|
1361
|
+
<button class="knowledge-chip-close" data-kb-id="${I(e.id)}" title="${r(`common.delete`)}">✕</button>
|
|
1362
1362
|
</span>
|
|
1363
1363
|
`}).join(``),e.querySelectorAll(`.knowledge-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),Bb(e.dataset.kbId)})}),e.style.display=`flex`}}var Ub={ok:!1,collections:[],ts:0},Wb=null,Gb=15e3;async function Kb(e=!1){let t=Date.now(),{ragEnabled:n}=await chrome.storage.local.get(`ragEnabled`);return n===!0?!e&&Ub.ts&&t-Ub.ts<Gb?Ub:Wb||(Wb=new Promise(e=>{try{chrome.runtime.sendMessage({type:`RAG_LIST_COLLECTIONS`},t=>{Ub=chrome.runtime.lastError||!t||!t.success?{ok:!1,collections:[],ts:Date.now()}:{ok:!0,collections:[...t.collections||[]].sort((e,t)=>(e.enabled===!1)-+(t.enabled===!1)),ts:Date.now()},e(Ub)})}catch{Ub={ok:!1,collections:[],ts:Date.now()},e(Ub)}}).finally(()=>{Wb=null}),Wb):{ok:!1,disabled:!0,collections:[],ts:Date.now()}}async function qb(e=``){let t=document.getElementById(`agentKnowledgeList`);if(!t)return;let n=await Kb();if(!n.ok){t.innerHTML=`<div class="prompt-empty">${r(n.disabled?`knowledgeSelector.disabled`:`knowledgeSelector.notAvailable`)}</div>`,C.selectedKnowledgeAtIndex=-1;return}let i=(e||``).toLowerCase(),a=n.collections.filter(t=>e?t.name&&t.name.toLowerCase().includes(i)||t.description&&t.description.toLowerCase().includes(i):!0);if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`knowledgeSelector.noCollections`)}</div>`,C.selectedKnowledgeAtIndex=-1;return}C.selectedKnowledgeAtIndex=0,t.innerHTML=a.map((e,t)=>{let n=C.knowledgeRefs.some(t=>t.id===e.id),i=r(`knowledgeSelector.docChunk`,{docs:e.documentCount||0,chunks:e.chunkCount||0}),a=e.enabled===!1;return`
|
|
1364
1364
|
<div class="prompt-item ${t===0?`selected`:``} ${n?`agent-at-active picked`:``} ${a?`knowledge-item-disabled`:``} prompt-item-knowledge"
|
|
1365
|
-
data-index="${t}" data-kb-id="${
|
|
1366
|
-
data-kb-disabled="${a?`1`:`0`}"${a?` title="${
|
|
1365
|
+
data-index="${t}" data-kb-id="${I(e.id)}" data-kb-name="${I(e.name||``)}"
|
|
1366
|
+
data-kb-disabled="${a?`1`:`0`}"${a?` title="${I(r(`knowledgeSelector.disabledTooltip`))}"`:``}>
|
|
1367
1367
|
<span class="prompt-item-index">${t+1}</span>
|
|
1368
1368
|
<span class="agent-at-icon">📚</span>
|
|
1369
|
-
<span class="prompt-item-content">${
|
|
1369
|
+
<span class="prompt-item-content">${I(e.name||``)}</span>
|
|
1370
1370
|
${a?`<span class="knowledge-item-badge badge-disabled">${r(`knowledgeSelector.disabledBadge`)}</span>`:``}
|
|
1371
|
-
<span class="prompt-item-code">${
|
|
1371
|
+
<span class="prompt-item-code">${I(i)}</span>
|
|
1372
1372
|
</div>
|
|
1373
|
-
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{zb({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&_b()})})}async function Jb(e,{clearTrigger:t=!0}={}){t?Pb():Fb(),_b();try{await chrome.storage.local.set({activeAgentId:e}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}),i.debug(`[AgentAtSelector] switched to agent:`,e)}catch(e){i.error(`[AgentAtSelector] switchagent failed:`,e)}
|
|
1373
|
+
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{zb({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&_b()})})}async function Jb(e,{clearTrigger:t=!0}={}){t?Pb():Fb(),_b();try{await chrome.storage.local.set({activeAgentId:e}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}),i.debug(`[AgentAtSelector] switched to agent:`,e)}catch(e){i.error(`[AgentAtSelector] switchagent failed:`,e)}lt()}var Yb=!1;function Xb(){Yb||(Yb=!0,chrome.tabs.onActivated.addListener(()=>{let e=document.getElementById(`agentAtSelector`);if(!e||e.style.display!==`block`||fb!==`pages`&&!mb)return;let t=document.getElementById(`userInput`);bb(t?xb(t.value):``)}))}Xb();async function Zb(e,t){let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=n.pairedAgents||[];switch(e){case`enable`:i=i.map(e=>e.id===t?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===t?{...e,disabled:!0}:e);let e=n.activeAgentId;n.activeAgentId===t&&(e=i.find(e=>e.id!==t&&!e.disabled)?.id||null),await chrome.storage.local.set({pairedAgents:i,activeAgentId:e||``}),e?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}case`delete`:{let e=i.find(e=>e.id===t),a=e?.url?`\n${r(`promptSelector.proxyAddress`)}: ${e.url}`:``;if(!await window.showCustomConfirm(r(`promptSelector.deleteProxyTitle`),r(`promptSelector.confirmDeleteProxy`,{name:e?.name||t,urlInfo:a})))return;i=i.filter(e=>e.id!==t);let o=n.activeAgentId===t?i.find(e=>!e.disabled)?.id||null:n.activeAgentId;await chrome.storage.local.set({pairedAgents:i,activeAgentId:o||``}),o?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:o}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}}let a=document.getElementById(`userInput`);await bb(a?xb(a.value):``)}n(`zh`,{pageSelector:{noOpenPages:`暂无打开的网页`,noTitle:`无标题`,currentTab:`当前`,openNewTab:`新建标签页`,interpretPage:`解读`,summarizePage:`总结`,translatePage:`翻译`,interpretMsg:`解读一下当前网页`,summarizeMsg:`总结一下当前网页`,translateMsg:`翻译一下当前网页`}}),n(`en`,{pageSelector:{noOpenPages:`No open pages`,noTitle:`Untitled`,currentTab:`Current`,openNewTab:`Open new tab`,interpretPage:`Interpret`,summarizePage:`Summarize`,translatePage:`Translate`,interpretMsg:`Interpret the current webpage`,summarizeMsg:`Summarize the current webpage`,translateMsg:`Translate the current webpage`}});async function Qb(){try{return[...await chrome.tabs.query({currentWindow:!0})].sort((e,t)=>e.active===t.active?0:e.active?-1:1)}catch(e){return i.error(`[PageSelector] getlabelpage failed:`,e),[]}}async function $b(e=``){let t=document.getElementById(`agentPageList`);if(!t)return;let n=await Qb(),i=e.toLowerCase(),a=n.filter(t=>{if(!t.url)return!1;if(!e)return!0;let n=(t.title||``).toLowerCase().includes(i),r=t.url.toLowerCase().includes(i);return n||r});if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`pageSelector.noOpenPages`)}</div>`,C.selectedPageIndex=-1;return}C.selectedPageIndex=0;let o=C.selectedPage?C.selectedPage.id:null;t.innerHTML=a.map((e,t)=>{let n=e.title||r(`pageSelector.noTitle`),i=e.url||``,a=e.favIconUrl?`<img src="${I(e.favIconUrl)}" width="16" height="16" style="flex-shrink:0;" class="favicon-img">`:`<span style="font-size:14px;flex-shrink:0;">🌐</span>`,s=e.active?`<span class="current-tab-badge">${r(`pageSelector.currentTab`)}</span>`:``,c=e.id===o;return`
|
|
1374
1374
|
<div class="prompt-item prompt-item-page ${t===0?`selected`:``}"
|
|
1375
1375
|
data-index="${t}" data-tab-id="${e.id}">
|
|
1376
1376
|
<span class="prompt-item-index">${t+1}</span>
|
|
1377
1377
|
${a}
|
|
1378
|
-
<span class="prompt-item-content" title="${
|
|
1378
|
+
<span class="prompt-item-content" title="${I(n)}">${I(n)}</span>
|
|
1379
1379
|
${s}
|
|
1380
|
-
<span class="prompt-item-code" title="${
|
|
1380
|
+
<span class="prompt-item-code" title="${I(i)}">${I(i)}</span>
|
|
1381
1381
|
${c?`<span class="page-item-actions"><span class="page-selected-mark">✓</span></span>`:``}
|
|
1382
1382
|
<span class="page-action-toolbar">
|
|
1383
1383
|
<span class="page-action-btn" data-action="interpret" data-tab-id="${e.id}" title="${r(`pageSelector.interpretPage`)}">${r(`pageSelector.interpretPage`)}</span>
|
|
@@ -1385,7 +1385,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1385
1385
|
<span class="page-action-btn" data-action="translate" data-tab-id="${e.id}" title="${r(`pageSelector.translatePage`)}">${r(`pageSelector.translatePage`)}</span>
|
|
1386
1386
|
</span>
|
|
1387
1387
|
</div>
|
|
1388
|
-
`}).join(``),t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),ix(parseInt(n.dataset.tabId),n.dataset.action);return}rx(parseInt(e.dataset.tabId))})})}function ex(e){e.forEach((e,t)=>{t===C.selectedPageIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function tx(e){C.selectedPage={id:e.id,title:e.title||r(`pageSelector.noTitle`),url:e.url||``,favIconUrl:e.favIconUrl||``};let t=document.getElementById(`pageIndicator`),n=document.getElementById(`pageIndicatorName`);if(t&&n){let e=C.selectedPage.title&&C.selectedPage.title!==r(`pageSelector.noTitle`)?C.selectedPage.title:``,i=C.selectedPage.url||``;e&&i?n.textContent=`${e} · ${i}`:n.textContent=e||i,t.style.display=`flex`}}function nx(){C.selectedPage=null,C.selectedPageIndex=-1;let e=document.getElementById(`pageIndicator`);e&&(e.style.display=`none`)}function rx(e){let t=document.getElementById(`userInput`),n=t?t.value:``,r=n.lastIndexOf(`@`);r!==-1&&(t.value=n.substring(0,r)),t&&(t.focus(),t.selectionStart=t.selectionEnd=t.value.length),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[PageSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}tx(e),_b(),t&&(t.focus(),Ue())})}function ix(e,t){let n={interpret:r(`pageSelector.interpretMsg`),summarize:r(`pageSelector.summarizeMsg`),translate:r(`pageSelector.translateMsg`)}[t];n&&chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[PageSelector] get tab info failed:`,chrome.runtime.lastError);return}tx(e),_b();let t=document.getElementById(`userInput`);t&&(t.value=n,Ue()),Sw()})}function ax(){let e=document.getElementById(`pageIndicatorClose`);e&&e.addEventListener(`click`,()=>{nx()})}var ox=new Map;function sx(e,t){return!e||!t?!0:t<=(ox.get(e)||0)?!1:(ox.set(e,t),!0)}n(`zh`,{msgFullscreen:{title:`全屏阅读`,btnTitle:`全屏查看本回答 (Alt+双击 / Alt+F)`,btnLabel:`全屏`,copy:`复制`,copyTitle:`复制回答内容(Ctrl/⌘+点击复制富文本)`,export:`导出`,exportTitle:`导出下载本回答`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,close:`退出全屏`,closeTitle:`退出全屏 (Esc)`}}),n(`en`,{msgFullscreen:{title:`Fullscreen Reading`,btnTitle:`View this answer fullscreen (Alt+Double-click / Alt+F)`,btnLabel:`Fullscreen`,copy:`Copy`,copyTitle:`Copy answer (Ctrl/Cmd+click for rich text)`,export:`Export`,exportTitle:`Export / download this answer`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,close:`Exit fullscreen`,closeTitle:`Exit fullscreen (Esc)`}});var cx=`messageFullscreenOverlay`,lx=`messageFullscreenBody`,ux=`messageFullscreenTitle`,dx=`messageFullscreenCopyBtn`,fx=`messageFullscreenCloseBtn`,px=`messageFullscreenExportBtn`,mx=`messageFullscreenExportDropdown`,hx=null,gx=null,_x=null,vx=!1,yx=null,bx=!1;function xx(){return hx!==null}function Sx(e){return!e||xx()?null:e.innerHTML}function Cx(){let e=document.querySelectorAll(`#chatContainer .message.assistant`);return e.length?e[e.length-1]:null}function wx(){let e=document.createElement(`button`);return e.className=`fullscreen-btn`,e.title=r(`msgFullscreen.btnTitle`),e.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">`,`<path d="M6 2H2v4M10 2h4v4M6 14H2v-4M10 14h4v-4"/>`,`</svg>`,`<span>${r(`msgFullscreen.btnLabel`)}</span>`].join(``),e}function Tx(){let e=document.getElementById(cx),t=document.getElementById(lx);return!e||!t?(i.warn(`[MsgFullscreen] overlay/body element missing`),null):{overlay:e,body:t,title:document.getElementById(ux),copyBtn:document.getElementById(dx),closeBtn:document.getElementById(fx)}}function Ex(e){if(!e)return;let t=Tx();if(t&&hx!==e){if(!hx){let e=document.getElementById(`chatContainer`);yx=e?e.scrollTop:null}hx&&(bx=!0,Dx(),bx=!1),gx=document.createComment(`msg-fullscreen-anchor`),e.parentNode.insertBefore(gx,e),e.dataset.fullscreen=`1`,t.body.appendChild(e),hx=e,t.overlay.style.display=`flex`,document.body.classList.add(`message-fullscreen-viewing`),t.title&&(t.title.textContent=r(`msgFullscreen.title`)),t.copyBtn&&(t.copyBtn.title=r(`msgFullscreen.copyTitle`)),t.closeBtn&&(t.closeBtn.title=r(`msgFullscreen.closeTitle`)),Lx(),kx(t.body)}}function Dx(){if(!hx)return;let e=Tx();if(jx(),Rx(),gx&&gx.parentNode)gx.parentNode.insertBefore(hx,gx);else if(e){let e=document.getElementById(`chatContainer`);e&&e.appendChild(hx)}if(gx&&gx.parentNode&&gx.parentNode.removeChild(gx),delete hx.dataset.fullscreen,hx=null,gx=null,e){e.overlay.style.display=`none`,e.body.innerHTML=``;let t=e.overlay.querySelector(`.message-fullscreen-rail`);t&&t.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}if(document.body.classList.remove(`message-fullscreen-viewing`),!bx&&yx!==null){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=yx),yx=null}}function Ox(e){if(hx&&hx===e){Dx();return}Ex(e||Cx())}function kx(e){jx(),vx=!1,e.scrollTop=e.scrollHeight,e.addEventListener(`scroll`,Ax,{passive:!0}),typeof ResizeObserver<`u`&&(_x=new ResizeObserver(()=>{vx||(e.scrollTop=e.scrollHeight)}),_x.observe(e.firstElementChild||e))}function Ax(){let e=document.getElementById(lx);e&&(vx=e.scrollHeight-e.scrollTop-e.clientHeight>60)}function jx(){let e=document.getElementById(lx);e&&e.removeEventListener(`scroll`,Ax),_x&&=(_x.disconnect(),null)}function Mx(e){if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyF`){e.preventDefault(),hx?Dx():Ex(Cx());return}e.key===`Escape`&&hx&&(e.preventDefault(),e.stopImmediatePropagation(),Dx())}function Nx(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let t=e.target.closest?.(`#chatContainer .message.assistant`);t&&(e.preventDefault(),Ox(t))}async function Px(e){if(!hx)return;let{copyAssistantMessage:t}=await A(async()=>{let{copyAssistantMessage:e}=await Promise.resolve().then(()=>Vx);return{copyAssistantMessage:e}},void 0);t(hx,document.getElementById(dx),e)}var Fx={docx:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6 8h4M6 10.5h4"/>`,pdf:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6.5 11.5c2-1 2.5-4 1-4s-1 4 2 4"/>`,image:`<rect x="2.5" y="3" width="11" height="10" rx="1.2"/><circle cx="6" cy="6.5" r="1"/><path d="M13.5 10 10 6.5 4.5 12.5"/>`,markdown:`<path d="M2.5 12V4l3 3 3-3v8"/><path d="M12.5 4v6m0 0 2-2.2m-2 2.2L10.5 7.8"/>`};function Ix(){let e=document.createElement(`div`);e.className=`message-fullscreen-export`;let t=document.createElement(`button`);t.className=`message-fullscreen-icon-btn`,t.id=px,t.type=`button`,t.title=r(`msgFullscreen.exportTitle`),t.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="16" height="16">`,`<path d="M8 2v8m0 0 3-3M8 10 5 7M2.5 13.5h11"/>`,`</svg>`,`<span>${r(`msgFullscreen.export`)}</span>`,`<svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`].join(``);let n=document.createElement(`div`);n.className=`message-fullscreen-export-dropdown`,n.id=mx;let i=e=>`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${Fx[e]}</svg>`;n.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">${i(`docx`)}<span>${r(`msgFullscreen.exportWord`)}</span></button>`,`<button class="export-dropdown-item export-pdf-item" type="button">${i(`pdf`)}<span>${r(`msgFullscreen.exportPdf`)}</span></button>`,`<button class="export-dropdown-item export-image-item" type="button">${i(`image`)}<span>${r(`msgFullscreen.exportImage`)}</span></button>`,`<button class="export-dropdown-item export-md-item" type="button">${i(`markdown`)}<span>${r(`msgFullscreen.exportMarkdown`)}</span></button>`].join(``),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.toggle(`show`)});let a=(e,t)=>{let r=n.querySelector(e);r.addEventListener(`click`,async e=>{e.stopPropagation(),hx&&(n.classList.remove(`show`),(await A(()=>import(`./chat-export-DIK7kXq9.js`),__vite__mapDeps([9,10,1,11,2,3,0])))[t](hx,r,n))})};return a(`.export-docx-item`,`exportAssistantMessageToDocx`),a(`.export-pdf-item`,`exportAssistantMessageToPdf`),a(`.export-image-item`,`exportAssistantMessageToImage`),a(`.export-md-item`,`exportAssistantMessageToMarkdown`),e.appendChild(t),e.appendChild(n),e}function Lx(){if(document.getElementById(px))return;let e=document.getElementById(fx),t=e?e.parentNode:document.querySelector(`.message-fullscreen-actions`);t&&t.insertBefore(Ix(),e||null)}function Rx(){let e=document.getElementById(mx);e&&e.classList.remove(`show`)}var zx=!1;function Bx(){zx||(zx=!0,document.addEventListener(`click`,e=>{let t=document.getElementById(mx);t&&t.classList.contains(`show`)&&!e.target.closest?.(`.message-fullscreen-export`)&&t.classList.remove(`show`);let n=e.target.closest?.(`.fullscreen-btn`);if(n){e.stopPropagation(),Ox(n.closest(`.message`));return}if(e.target.closest?.(`#messageFullscreenCloseBtn`)){e.stopPropagation(),Dx();return}e.target.closest?.(`#messageFullscreenCopyBtn`)&&(e.stopPropagation(),Px(e))},!0),document.addEventListener(`keydown`,Mx,!0),document.addEventListener(`dblclick`,Nx,!0))}var Vx=t({copyAssistantMessage:()=>Wx,copyMessage:()=>Ux,copyRichText:()=>qx,fallbackCopyRichText:()=>Yx,fallbackCopyText:()=>Kx,quoteAndAsk:()=>Qx,setQuoteContextInjector:()=>Zx,showCopySuccess:()=>Gx,wrapHtmlWithStyles:()=>Jx});n(`zh`,{chatCopy:{copiedMarkdown:`已复制 Markdown`,copiedRich:`已复制富文本`,copyFailedManual:`复制失败,请手动复制`}}),n(`en`,{chatCopy:{copiedMarkdown:`Markdown copied`,copiedRich:`Rich text copied`,copyFailedManual:`Copy failed, please copy manually`}});function Hx(e){let t=e.querySelectorAll(`.mermaid`),n=null;for(let e of t)try{if(!n&&e._pngDataUrl){let t=e._pngDataUrl.split(`,`)[1]||``,r=atob(t),i=r.length,a=new Uint8Array(i);for(let e=0;e<i;e++)a[e]=r.charCodeAt(e);n=new Blob([a],{type:`image/png`})}let t=e.getAttribute(`data-raw-code`),r=t?decodeURIComponent(t):e.dataset.rawMermaidCode||(e.textContent||``).trim();if(r){let t=r.split(`
|
|
1388
|
+
`}).join(``),t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),ix(parseInt(n.dataset.tabId),n.dataset.action);return}rx(parseInt(e.dataset.tabId))})})}function ex(e){e.forEach((e,t)=>{t===C.selectedPageIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function tx(e){C.selectedPage={id:e.id,title:e.title||r(`pageSelector.noTitle`),url:e.url||``,favIconUrl:e.favIconUrl||``};let t=document.getElementById(`pageIndicator`),n=document.getElementById(`pageIndicatorName`);if(t&&n){let e=C.selectedPage.title&&C.selectedPage.title!==r(`pageSelector.noTitle`)?C.selectedPage.title:``,i=C.selectedPage.url||``;e&&i?n.textContent=`${e} · ${i}`:n.textContent=e||i,t.style.display=`flex`}}function nx(){C.selectedPage=null,C.selectedPageIndex=-1;let e=document.getElementById(`pageIndicator`);e&&(e.style.display=`none`)}function rx(e){let t=document.getElementById(`userInput`),n=t?t.value:``,r=n.lastIndexOf(`@`);r!==-1&&(t.value=n.substring(0,r)),t&&(t.focus(),t.selectionStart=t.selectionEnd=t.value.length),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[PageSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}tx(e),_b(),t&&(t.focus(),lt())})}function ix(e,t){let n={interpret:r(`pageSelector.interpretMsg`),summarize:r(`pageSelector.summarizeMsg`),translate:r(`pageSelector.translateMsg`)}[t];n&&chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[PageSelector] get tab info failed:`,chrome.runtime.lastError);return}tx(e),_b();let t=document.getElementById(`userInput`);t&&(t.value=n,lt()),Sw()})}function ax(){let e=document.getElementById(`pageIndicatorClose`);e&&e.addEventListener(`click`,()=>{nx()})}var ox=new Map;function sx(e,t){return!e||!t?!0:t<=(ox.get(e)||0)?!1:(ox.set(e,t),!0)}n(`zh`,{msgFullscreen:{title:`全屏阅读`,btnTitle:`全屏查看本回答 (Alt+双击 / Alt+F)`,btnLabel:`全屏`,copy:`复制`,copyTitle:`复制回答内容(Ctrl/⌘+点击复制富文本)`,export:`导出`,exportTitle:`导出下载本回答`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,close:`退出全屏`,closeTitle:`退出全屏 (Esc)`}}),n(`en`,{msgFullscreen:{title:`Fullscreen Reading`,btnTitle:`View this answer fullscreen (Alt+Double-click / Alt+F)`,btnLabel:`Fullscreen`,copy:`Copy`,copyTitle:`Copy answer (Ctrl/Cmd+click for rich text)`,export:`Export`,exportTitle:`Export / download this answer`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,close:`Exit fullscreen`,closeTitle:`Exit fullscreen (Esc)`}});var cx=`messageFullscreenOverlay`,lx=`messageFullscreenBody`,ux=`messageFullscreenTitle`,dx=`messageFullscreenCopyBtn`,fx=`messageFullscreenCloseBtn`,px=`messageFullscreenExportBtn`,mx=`messageFullscreenExportDropdown`,hx=null,gx=null,_x=null,vx=!1,yx=null,bx=!1;function xx(){return hx!==null}function Sx(e){return!e||xx()?null:e.innerHTML}function Cx(){let e=document.querySelectorAll(`#chatContainer .message.assistant`);return e.length?e[e.length-1]:null}function wx(){let e=document.createElement(`button`);return e.className=`fullscreen-btn`,e.title=r(`msgFullscreen.btnTitle`),e.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">`,`<path d="M6 2H2v4M10 2h4v4M6 14H2v-4M10 14h4v-4"/>`,`</svg>`,`<span>${r(`msgFullscreen.btnLabel`)}</span>`].join(``),e}function Tx(){let e=document.getElementById(cx),t=document.getElementById(lx);return!e||!t?(i.warn(`[MsgFullscreen] overlay/body element missing`),null):{overlay:e,body:t,title:document.getElementById(ux),copyBtn:document.getElementById(dx),closeBtn:document.getElementById(fx)}}function Ex(e){if(!e)return;let t=Tx();if(t&&hx!==e){if(!hx){let e=document.getElementById(`chatContainer`);yx=e?e.scrollTop:null}hx&&(bx=!0,Dx(),bx=!1),gx=document.createComment(`msg-fullscreen-anchor`),e.parentNode.insertBefore(gx,e),e.dataset.fullscreen=`1`,t.body.appendChild(e),hx=e,t.overlay.style.display=`flex`,document.body.classList.add(`message-fullscreen-viewing`),t.title&&(t.title.textContent=r(`msgFullscreen.title`)),t.copyBtn&&(t.copyBtn.title=r(`msgFullscreen.copyTitle`)),t.closeBtn&&(t.closeBtn.title=r(`msgFullscreen.closeTitle`)),Lx(),kx(t.body)}}function Dx(){if(!hx)return;let e=Tx();if(jx(),Rx(),gx&&gx.parentNode)gx.parentNode.insertBefore(hx,gx);else if(e){let e=document.getElementById(`chatContainer`);e&&e.appendChild(hx)}if(gx&&gx.parentNode&&gx.parentNode.removeChild(gx),delete hx.dataset.fullscreen,hx=null,gx=null,e){e.overlay.style.display=`none`,e.body.innerHTML=``;let t=e.overlay.querySelector(`.message-fullscreen-rail`);t&&t.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}if(document.body.classList.remove(`message-fullscreen-viewing`),!bx&&yx!==null){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=yx),yx=null}}function Ox(e){if(hx&&hx===e){Dx();return}Ex(e||Cx())}function kx(e){jx(),vx=!1,e.scrollTop=e.scrollHeight,e.addEventListener(`scroll`,Ax,{passive:!0}),typeof ResizeObserver<`u`&&(_x=new ResizeObserver(()=>{vx||(e.scrollTop=e.scrollHeight)}),_x.observe(e.firstElementChild||e))}function Ax(){let e=document.getElementById(lx);e&&(vx=e.scrollHeight-e.scrollTop-e.clientHeight>60)}function jx(){let e=document.getElementById(lx);e&&e.removeEventListener(`scroll`,Ax),_x&&=(_x.disconnect(),null)}function Mx(e){if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyF`){e.preventDefault(),hx?Dx():Ex(Cx());return}e.key===`Escape`&&hx&&(e.preventDefault(),e.stopImmediatePropagation(),Dx())}function Nx(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let t=e.target.closest?.(`#chatContainer .message.assistant`);t&&(e.preventDefault(),Ox(t))}async function Px(e){if(!hx)return;let{copyAssistantMessage:t}=await A(async()=>{let{copyAssistantMessage:e}=await Promise.resolve().then(()=>Vx);return{copyAssistantMessage:e}},void 0);t(hx,document.getElementById(dx),e)}var Fx={docx:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6 8h4M6 10.5h4"/>`,pdf:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6.5 11.5c2-1 2.5-4 1-4s-1 4 2 4"/>`,image:`<rect x="2.5" y="3" width="11" height="10" rx="1.2"/><circle cx="6" cy="6.5" r="1"/><path d="M13.5 10 10 6.5 4.5 12.5"/>`,markdown:`<path d="M2.5 12V4l3 3 3-3v8"/><path d="M12.5 4v6m0 0 2-2.2m-2 2.2L10.5 7.8"/>`};function Ix(){let e=document.createElement(`div`);e.className=`message-fullscreen-export`;let t=document.createElement(`button`);t.className=`message-fullscreen-icon-btn`,t.id=px,t.type=`button`,t.title=r(`msgFullscreen.exportTitle`),t.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="16" height="16">`,`<path d="M8 2v8m0 0 3-3M8 10 5 7M2.5 13.5h11"/>`,`</svg>`,`<span>${r(`msgFullscreen.export`)}</span>`,`<svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`].join(``);let n=document.createElement(`div`);n.className=`message-fullscreen-export-dropdown`,n.id=mx;let i=e=>`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${Fx[e]}</svg>`;n.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">${i(`docx`)}<span>${r(`msgFullscreen.exportWord`)}</span></button>`,`<button class="export-dropdown-item export-pdf-item" type="button">${i(`pdf`)}<span>${r(`msgFullscreen.exportPdf`)}</span></button>`,`<button class="export-dropdown-item export-image-item" type="button">${i(`image`)}<span>${r(`msgFullscreen.exportImage`)}</span></button>`,`<button class="export-dropdown-item export-md-item" type="button">${i(`markdown`)}<span>${r(`msgFullscreen.exportMarkdown`)}</span></button>`].join(``),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.toggle(`show`)});let a=(e,t)=>{let r=n.querySelector(e);r.addEventListener(`click`,async e=>{e.stopPropagation(),hx&&(n.classList.remove(`show`),(await A(()=>import(`./chat-export-DZntnUPd.js`),__vite__mapDeps([9,10,1,11,2,3,12,0])))[t](hx,r,n))})};return a(`.export-docx-item`,`exportAssistantMessageToDocx`),a(`.export-pdf-item`,`exportAssistantMessageToPdf`),a(`.export-image-item`,`exportAssistantMessageToImage`),a(`.export-md-item`,`exportAssistantMessageToMarkdown`),e.appendChild(t),e.appendChild(n),e}function Lx(){if(document.getElementById(px))return;let e=document.getElementById(fx),t=e?e.parentNode:document.querySelector(`.message-fullscreen-actions`);t&&t.insertBefore(Ix(),e||null)}function Rx(){let e=document.getElementById(mx);e&&e.classList.remove(`show`)}var zx=!1;function Bx(){zx||(zx=!0,document.addEventListener(`click`,e=>{let t=document.getElementById(mx);t&&t.classList.contains(`show`)&&!e.target.closest?.(`.message-fullscreen-export`)&&t.classList.remove(`show`);let n=e.target.closest?.(`.fullscreen-btn`);if(n){e.stopPropagation(),Ox(n.closest(`.message`));return}if(e.target.closest?.(`#messageFullscreenCloseBtn`)){e.stopPropagation(),Dx();return}e.target.closest?.(`#messageFullscreenCopyBtn`)&&(e.stopPropagation(),Px(e))},!0),document.addEventListener(`keydown`,Mx,!0),document.addEventListener(`dblclick`,Nx,!0))}var Vx=t({copyAssistantMessage:()=>Wx,copyMessage:()=>Ux,copyRichText:()=>qx,fallbackCopyRichText:()=>Yx,fallbackCopyText:()=>Kx,quoteAndAsk:()=>Qx,setQuoteContextInjector:()=>Zx,showCopySuccess:()=>Gx,wrapHtmlWithStyles:()=>Jx});n(`zh`,{chatCopy:{copiedMarkdown:`已复制 Markdown`,copiedRich:`已复制富文本`,copyFailedManual:`复制失败,请手动复制`}}),n(`en`,{chatCopy:{copiedMarkdown:`Markdown copied`,copiedRich:`Rich text copied`,copyFailedManual:`Copy failed, please copy manually`}});function Hx(e){let t=e.querySelectorAll(`.mermaid`),n=null;for(let e of t)try{if(!n&&e._pngDataUrl){let t=e._pngDataUrl.split(`,`)[1]||``,r=atob(t),i=r.length,a=new Uint8Array(i);for(let e=0;e<i;e++)a[e]=r.charCodeAt(e);n=new Blob([a],{type:`image/png`})}let t=e.getAttribute(`data-raw-code`),r=t?decodeURIComponent(t):e.dataset.rawMermaidCode||(e.textContent||``).trim();if(r){let t=r.split(`
|
|
1389
1389
|
`),n=document.createElement(`pre`);n.appendChild(document.createTextNode(t[0]||``));for(let e=1;e<t.length;e++)n.appendChild(document.createElement(`br`)),n.appendChild(document.createTextNode(t[e]));e.parentNode.replaceChild(n,e)}else e.remove()}catch(t){i.warn(`[SidePanel] Mermaid chartprocessing failed,remove:`,t.message),e.remove()}return{html:e.innerHTML,firstPngBlob:n}}function Ux(e,t){try{let n=e.dataset.textContent_||e.dataset.rawContent||``;navigator.clipboard.writeText(n).then(()=>{let e=t.innerHTML;t.innerHTML=`
|
|
1390
1390
|
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
1391
1391
|
<path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0z"/>
|
|
@@ -1394,12 +1394,12 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1394
1394
|
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
1395
1395
|
<path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0z"/>
|
|
1396
1396
|
</svg>
|
|
1397
|
-
`,t.classList.add(`copied`),setTimeout(()=>{t.innerHTML=e,t.classList.remove(`copied`)},2e3)}catch{
|
|
1397
|
+
`,t.classList.add(`copied`),setTimeout(()=>{t.innerHTML=e,t.classList.remove(`copied`)},2e3)}catch{P(r(`chatCopy.copyFailed`),`error`)}document.body.removeChild(a)})}catch(e){i.error(`[SidePanel] copy failed:`,e),P(r(`chatCopy.copyFailed`),`error`)}}function Wx(e,t,n){try{let r=e.dataset.rawMarkdown||e.dataset.rawContent||``,i=``;if(!r){let t=C.messageHistory.find(e=>e.role===`assistant`);if(t)r=t.content;else{let t=e.querySelector(`.final-answer .markdown-body`)||e.querySelector(`.markdown-body`);t?(r=t.innerText,i=t.innerHTML):(r=e.innerText,i=e.innerHTML)}}if(!i){let t=e.querySelector(`.final-answer .markdown-body`)||e.querySelector(`.markdown-body`);t?i=t.innerHTML:r&&(i=et(r))}if(n&&(n.ctrlKey||n.metaKey)&&i){let e=document.createElement(`div`);e.innerHTML=i,e.querySelectorAll(`table`).forEach(e=>{let t=it(e);e.parentNode.replaceChild(t,e)});let{html:n,firstPngBlob:a}=Hx(e);qx(r,n,t,a)}else navigator.clipboard.writeText(r).then(()=>{t&&Gx(t)}).catch(()=>{Kx(r,t)})}catch(e){i.error(`[SidePanel] copy failed:`,e),P(r(`chatCopy.copyFailed`),`error`)}}function Gx(e,t=!1){let n=e.innerHTML;e.innerHTML=`
|
|
1398
1398
|
<svg viewBox="0 0 16 16" fill="currentColor">
|
|
1399
1399
|
<path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0z"/>
|
|
1400
1400
|
</svg>
|
|
1401
1401
|
<span>${r(t?`chatCopy.copiedRich`:`chatCopy.copiedMarkdown`)}</span>
|
|
1402
|
-
`,e.classList.add(`copied`),setTimeout(()=>{e.innerHTML=n,e.classList.remove(`copied`)},2e3)}function Kx(e,t){let n=document.createElement(`textarea`);n.value=e,n.style.position=`fixed`,n.style.left=`-999999px`,document.body.appendChild(n),n.select();try{document.execCommand(`copy`),Gx(t)}catch{
|
|
1402
|
+
`,e.classList.add(`copied`),setTimeout(()=>{e.innerHTML=n,e.classList.remove(`copied`)},2e3)}function Kx(e,t){let n=document.createElement(`textarea`);n.value=e,n.style.position=`fixed`,n.style.left=`-999999px`,document.body.appendChild(n),n.select();try{document.execCommand(`copy`),Gx(t)}catch{P(r(`chatCopy.copyFailedManual`),`error`)}document.body.removeChild(n)}function qx(e,t,n,r=null){let a=Jx(t);if(n&&!document.hasFocus()&&n.focus(),typeof ClipboardItem<`u`){let t={"text/plain":new Blob([e],{type:`text/plain`}),"text/html":new Blob([a],{type:`text/html`})};r&&(t[`image/png`]=r);let o=new ClipboardItem(t);navigator.clipboard.write([o]).then(()=>{Gx(n,!0)}).catch(t=>{i.warn(`[SidePanel] Clipboard API write failed,using fallback plan:`,t.message),Yx(e,a,n)})}else Yx(e,a,n)}function Jx(e){return`<!DOCTYPE html><html><head>
|
|
1403
1403
|
<style>
|
|
1404
1404
|
h1 { font-size: 24px; font-weight: bold; margin: 16px 0 8px; }
|
|
1405
1405
|
h2 { font-size: 20px; font-weight: bold; margin: 14px 0 6px; }
|
|
@@ -1443,13 +1443,13 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1443
1443
|
<path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0z"/>
|
|
1444
1444
|
</svg>
|
|
1445
1445
|
<span>${r(`chatCopy.quoted`)}</span>
|
|
1446
|
-
`,a.classList.add(`quoted`),setTimeout(()=>{a.innerHTML=o,a.classList.remove(`quoted`)},2e3)),n.focus(),i.debug(`[SidePanel] quote with messagecontent to prompt,input boxfocused`)}catch(e){i.error(`[SidePanel] quoted question failed:`,e),
|
|
1446
|
+
`,a.classList.add(`quoted`),setTimeout(()=>{a.innerHTML=o,a.classList.remove(`quoted`)},2e3)),n.focus(),i.debug(`[SidePanel] quote with messagecontent to prompt,input boxfocused`)}catch(e){i.error(`[SidePanel] quoted question failed:`,e),P(r(`chatCopy.quoteFailed`,{message:e.message}),`error`)}}n(`zh`,{chatPanels:{decisionPassed:`通过`,decisionRevised:`已修订`,decisionNeedsImprovement:`需改进`,dimAccuracy:`准确性`,dimCompleteness:`完整性`,dimRelevance:`相关性`,dimClarity:`清晰度`,dimUsefulness:`实用性`,dimSafety:`安全性`,dimEfficiency:`效率`,dimensionsTitle:`📊 评分维度`,issuesTitle:`❗ 发现的问题`,suggestionsTitle:`💡 改进建议`,roundsEvaluated:`评估 {rounds} 轮{revised}`,revisedTag:`(已修订)`,finalDecision:`最终决策:{label}`,resultUseful:`结果可用`,resultNeedsImprovement:`结果需改进`,processTitle:`🔄 评估过程`,scoreHighExplanation:`回答质量较高,内容准确、完整且清晰。`,scoreMidExplanation:`回答基本可用,但存在一些可以改进的地方。`,scoreLowExplanation:`回答质量较低,存在明显问题需要改进。`,reflectionTitle:`💡 质量评估详情`,overallScore:`综合评分`,scoreExplanationTitle:`📝 评分说明`,aboutTitle:`ℹ️ 关于质量评估`,aboutDesc:`质量评估由 AI 自动完成,从多个维度对回答进行打分,帮助判断回答的可靠程度。`,scoreStandard:`评分标准:8-10 分优秀,5-7 分良好,1-4 分需改进。`,executionLogTitle:`执行日志`,taskBreakdown:`任务拆解`,totalDurationTitle:`总耗时:{duration}`,totalDuration:`总耗时`,totalNodesTitle:`共 {count} 个执行节点`,totalNodes:`执行节点`,successCountTitle:`成功 {count} 个`,successLabel:`成功`,failedCountTitle:`失败 {count} 个`,failedLabel:`失败`,subtaskCountTitle:`子任务 {completed}/{total} 完成`,subtaskLabel:`子任务`,scoreTitle:`评分 {score}/10`,scoreLabel:`评分`,scoreUnavailable:`—`,tokenUsage:`Token 消耗`,tokenUsageTitle:`Token 消耗: {total} (Prompt: {prompt}, Completion: {completion})`,expandAll:`展开全部`,collapseAll:`收起全部`}}),n(`en`,{chatPanels:{decisionPassed:`Passed`,decisionRevised:`Revised`,decisionNeedsImprovement:`Needs Improvement`,dimAccuracy:`Accuracy`,dimCompleteness:`Completeness`,dimRelevance:`Relevance`,dimClarity:`Clarity`,dimUsefulness:`Usefulness`,dimSafety:`Safety`,dimEfficiency:`Efficiency`,dimensionsTitle:`📊 Scoring Dimensions`,issuesTitle:`❗ Issues Found`,suggestionsTitle:`💡 Suggestions`,roundsEvaluated:`Evaluated {rounds} rounds{revised}`,revisedTag:` (revised)`,finalDecision:`Final Decision: {label}`,resultUseful:`Result is useful`,resultNeedsImprovement:`Result needs improvement`,processTitle:`🔄 Evaluation Process`,scoreHighExplanation:`The answer is high quality, accurate, complete, and clear.`,scoreMidExplanation:`The answer is generally usable but has room for improvement.`,scoreLowExplanation:`The answer is low quality with obvious issues that need improvement.`,reflectionTitle:`💡 Quality Assessment Details`,overallScore:`Overall Score`,scoreExplanationTitle:`📝 Score Explanation`,aboutTitle:`ℹ️ About Quality Assessment`,aboutDesc:`Quality assessment is performed automatically by AI, scoring answers across multiple dimensions to help judge reliability.`,scoreStandard:`Scoring: 8-10 excellent, 5-7 good, 1-4 needs improvement.`,executionLogTitle:`Execution Log`,taskBreakdown:`Task Breakdown`,totalDurationTitle:`Total duration: {duration}`,totalDuration:`Duration`,totalNodesTitle:`{count} execution nodes`,totalNodes:`Nodes`,successCountTitle:`{count} succeeded`,successLabel:`Success`,failedCountTitle:`{count} failed`,failedLabel:`Failed`,subtaskCountTitle:`Subtasks {completed}/{total} done`,subtaskLabel:`Subtasks`,scoreTitle:`Score {score}/10`,scoreLabel:`Score`,scoreUnavailable:`—`,tokenUsage:`Token Usage`,tokenUsageTitle:`Token usage: {total} (Prompt: {prompt}, Completion: {completion})`,expandAll:`Expand All`,collapseAll:`Collapse All`}});function $x(e,t){let n=document.querySelector(`.reflection-info-overlay`);n&&n.remove();let i=document.createElement(`div`);i.className=`reflection-info-overlay`;let{overallScore:a,dimensions:o,issues:s,suggestions:c,decision:l,useful:u,reasoning:d,suggestion:f,rounds:p,wasRevised:m}=e,h=a>=8?`score-high`:a>=5?`score-mid`:`score-low`,g=a>=8?`✅`:a>=5?`🔍`:`⚠️`,_=l===`passed`?r(`chatPanels.decisionPassed`):l===`revised`?r(`chatPanels.decisionRevised`):l===`needs_improvement`?r(`chatPanels.decisionNeedsImprovement`):``,v={accuracy:r(`chatPanels.dimAccuracy`),completeness:r(`chatPanels.dimCompleteness`),relevance:r(`chatPanels.dimRelevance`),clarity:r(`chatPanels.dimClarity`),usefulness:r(`chatPanels.dimUsefulness`),safety:r(`chatPanels.dimSafety`),efficiency:r(`chatPanels.dimEfficiency`)},y=``;o&&Object.keys(o).length>0&&(y=`
|
|
1447
1447
|
<div class="ri-section">
|
|
1448
1448
|
<div class="ri-section-title">${r(`chatPanels.dimensionsTitle`)}</div>
|
|
1449
1449
|
<div class="ri-dimensions">
|
|
1450
1450
|
${Object.entries(o).map(([e,t])=>{let n=v[e]||e,r=t>=8?`#10b981`:t>=5?`#f59e0b`:`#ef4444`;return`
|
|
1451
1451
|
<div class="ri-dim-item">
|
|
1452
|
-
<span class="ri-dim-label">${
|
|
1452
|
+
<span class="ri-dim-label">${I(n)}</span>
|
|
1453
1453
|
<span class="ri-dim-bar-bg"><span class="ri-dim-bar-fill" style="width:${t*10}%;background:${r}"></span></span>
|
|
1454
1454
|
<span class="ri-dim-score" style="color:${r}">${t}/10</span>
|
|
1455
1455
|
</div>
|
|
@@ -1459,14 +1459,14 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1459
1459
|
`);let b=``;s&&s.length>0&&(b=`
|
|
1460
1460
|
<div class="ri-section">
|
|
1461
1461
|
<div class="ri-section-title">${r(`chatPanels.issuesTitle`)}</div>
|
|
1462
|
-
<ul class="ri-list">${s.map(e=>`<li>${
|
|
1462
|
+
<ul class="ri-list">${s.map(e=>`<li>${I(e)}</li>`).join(``)}</ul>
|
|
1463
1463
|
</div>
|
|
1464
1464
|
`);let x=``;c&&c.length>0&&(x=`
|
|
1465
1465
|
<div class="ri-section">
|
|
1466
1466
|
<div class="ri-section-title">${r(`chatPanels.suggestionsTitle`)}</div>
|
|
1467
|
-
<ul class="ri-list">${c.map(e=>`<li>${
|
|
1467
|
+
<ul class="ri-list">${c.map(e=>`<li>${I(e)}</li>`).join(``)}</ul>
|
|
1468
1468
|
</div>
|
|
1469
|
-
`);let S=``;if(p>0||l||u!==null){let e=[];p>0&&e.push(`<span class="ri-tag">${r(`chatPanels.roundsEvaluated`,{rounds:p,revised:m?r(`chatPanels.revisedTag`):``})}</span>`),l&&e.push(`<span class="ri-tag">${r(`chatPanels.finalDecision`,{label:_})}</span>`),u!==null&&e.push(`<span class="ri-tag">${r(u?`chatPanels.resultUseful`:`chatPanels.resultNeedsImprovement`)}</span>`),d&&e.push(`<div class="ri-reasoning">📝 ${
|
|
1469
|
+
`);let S=``;if(p>0||l||u!==null){let e=[];p>0&&e.push(`<span class="ri-tag">${r(`chatPanels.roundsEvaluated`,{rounds:p,revised:m?r(`chatPanels.revisedTag`):``})}</span>`),l&&e.push(`<span class="ri-tag">${r(`chatPanels.finalDecision`,{label:_})}</span>`),u!==null&&e.push(`<span class="ri-tag">${r(u?`chatPanels.resultUseful`:`chatPanels.resultNeedsImprovement`)}</span>`),d&&e.push(`<div class="ri-reasoning">📝 ${I(d)}</div>`),S=`
|
|
1470
1470
|
<div class="ri-section">
|
|
1471
1471
|
<div class="ri-section-title">${r(`chatPanels.processTitle`)}</div>
|
|
1472
1472
|
<div class="ri-process">${e.join(``)}</div>
|
|
@@ -1498,7 +1498,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1498
1498
|
</div>
|
|
1499
1499
|
</div>
|
|
1500
1500
|
</div>
|
|
1501
|
-
`,document.body.appendChild(i),i.querySelector(`.ri-close`).addEventListener(`click`,()=>i.remove()),i.addEventListener(`click`,e=>{e.target===i&&i.remove()});let w=t.getBoundingClientRect(),T=i.querySelector(`.reflection-info-panel`),E=Math.min(window.innerHeight-40,560),D=w.right-380;D<10&&(D=10),D+380>window.innerWidth-10&&(D=window.innerWidth-380-10);let O=w.bottom+6;O+E>window.innerHeight-10&&(O=w.top-E-6),O<10&&(O=10),T.style.left=D+`px`,T.style.top=O+`px`,T.style.maxHeight=E+`px`}function eS(e){let t=document.querySelector(`.execution-log-panel`);t&&t.remove();let n=document.createElement(`div`);n.className=`execution-log-panel`;let i=e.reduce((e,t)=>e+(t.duration||0),0),a=e.filter(e=>e.status===`success`).length,o=e.filter(e=>e.status===`failed`).length,s=e.filter(e=>e.nodeType===`subtask`).length,c=e.filter(e=>e.nodeType===`subtask`&&e.status===`success`).length,l=e.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`plan_task`&&e.status===`success`).length,u=e.filter(e=>e.nodeType===`reflection`).find(e=>e.reflectionType===`post`),d=u&&u.overallScore!=null?`${u.overallScore}/10`:r(`chatPanels.scoreUnavailable`),f=
|
|
1501
|
+
`,document.body.appendChild(i),i.querySelector(`.ri-close`).addEventListener(`click`,()=>i.remove()),i.addEventListener(`click`,e=>{e.target===i&&i.remove()});let w=t.getBoundingClientRect(),T=i.querySelector(`.reflection-info-panel`),E=Math.min(window.innerHeight-40,560),D=w.right-380;D<10&&(D=10),D+380>window.innerWidth-10&&(D=window.innerWidth-380-10);let O=w.bottom+6;O+E>window.innerHeight-10&&(O=w.top-E-6),O<10&&(O=10),T.style.left=D+`px`,T.style.top=O+`px`,T.style.maxHeight=E+`px`}function eS(e){let t=document.querySelector(`.execution-log-panel`);t&&t.remove();let n=document.createElement(`div`);n.className=`execution-log-panel`;let i=e.reduce((e,t)=>e+(t.duration||0),0),a=e.filter(e=>e.status===`success`).length,o=e.filter(e=>e.status===`failed`).length,s=e.filter(e=>e.nodeType===`subtask`).length,c=e.filter(e=>e.nodeType===`subtask`&&e.status===`success`).length,l=e.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`plan_task`&&e.status===`success`).length,u=e.filter(e=>e.nodeType===`reflection`).find(e=>e.reflectionType===`post`),d=u&&u.overallScore!=null?`${u.overallScore}/10`:r(`chatPanels.scoreUnavailable`),f=We(e);n.innerHTML=`
|
|
1502
1502
|
<div class="log-container">
|
|
1503
1503
|
<div class="log-header">
|
|
1504
1504
|
<div class="log-title">
|
|
@@ -1518,19 +1518,19 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1518
1518
|
</div>
|
|
1519
1519
|
|
|
1520
1520
|
<div class="log-summary">
|
|
1521
|
-
<div class="summary-item" title="${r(`chatPanels.totalDurationTitle`,{duration:
|
|
1521
|
+
<div class="summary-item" title="${r(`chatPanels.totalDurationTitle`,{duration:Be(i)})}">
|
|
1522
1522
|
<svg class="summary-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1523
1523
|
<circle cx="12" cy="12" r="10"></circle>
|
|
1524
1524
|
<polyline points="12 6 12 12 16 14"></polyline>
|
|
1525
1525
|
</svg>
|
|
1526
1526
|
<span class="summary-label">${r(`chatPanels.totalDuration`)}</span>
|
|
1527
|
-
<span class="summary-value">${
|
|
1527
|
+
<span class="summary-value">${Be(i)}</span>
|
|
1528
1528
|
</div>
|
|
1529
1529
|
${f?`
|
|
1530
|
-
<div class="summary-item token-summary" title="${r(`chatPanels.tokenUsageTitle`,{total:
|
|
1530
|
+
<div class="summary-item token-summary" title="${r(`chatPanels.tokenUsageTitle`,{total:F(f.totalTokens),prompt:F(f.promptTokens),completion:F(f.completionTokens)})}">
|
|
1531
1531
|
<span class="summary-icon token-summary-icon">⬤</span>
|
|
1532
1532
|
<span class="summary-label">${r(`chatPanels.tokenUsage`)}</span>
|
|
1533
|
-
<span class="summary-value">${
|
|
1533
|
+
<span class="summary-value">${F(f.totalTokens)}</span>
|
|
1534
1534
|
</div>
|
|
1535
1535
|
`:``}
|
|
1536
1536
|
<div class="summary-combo" title="${r(`chatPanels.totalNodesTitle`,{count:e.length})}">
|
|
@@ -1585,11 +1585,11 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1585
1585
|
<polygon points="5 3 19 12 5 21 5 3"></polygon>
|
|
1586
1586
|
</svg>
|
|
1587
1587
|
<span>${r(`chatMsg.resumeTaskBtn`)}</span>
|
|
1588
|
-
`,o.addEventListener(`click`,async e=>{if(e.stopPropagation(),o.disabled)return;let t=await tS({budgetEnded:a});t!==null&&(o.disabled=!0,o.style.opacity=`0.6`,o.style.cursor=`not-allowed`,oS(C.activeSessionId,t).finally(()=>{o.disabled=!1,o.style.opacity=``,o.style.cursor=``}))}),n.appendChild(o),e.dataset.resumable=String(t),rS(e,C.activeSessionId),o}async function aS(){let e=C.activeSessionId;if(!e||C.pendingCallApiSessionIds&&C.pendingCallApiSessionIds.has(e))return;let t=C.messageHistory.some(e=>e.resumable),n=document.getElementById(`chatContainer`),a=n&&n.querySelector(`.resume-task-btn`);if(!(t&&a))try{let a=await chrome.runtime.sendMessage({type:`GET_CHECKPOINT`,sessionId:e});if(a?.running)return;if(a?.exists){i.debug(`[SidePanel] found abandoned checkpoint,auto addrestorehint card`),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}));let o=a.checkpoint,s=o.updatedAt?
|
|
1588
|
+
`,o.addEventListener(`click`,async e=>{if(e.stopPropagation(),o.disabled)return;let t=await tS({budgetEnded:a});t!==null&&(o.disabled=!0,o.style.opacity=`0.6`,o.style.cursor=`not-allowed`,oS(C.activeSessionId,t).finally(()=>{o.disabled=!1,o.style.opacity=``,o.style.cursor=``}))}),n.appendChild(o),e.dataset.resumable=String(t),rS(e,C.activeSessionId),o}async function aS(){let e=C.activeSessionId;if(!e||C.pendingCallApiSessionIds&&C.pendingCallApiSessionIds.has(e))return;let t=C.messageHistory.some(e=>e.resumable),n=document.getElementById(`chatContainer`),a=n&&n.querySelector(`.resume-task-btn`);if(!(t&&a))try{let a=await chrome.runtime.sendMessage({type:`GET_CHECKPOINT`,sessionId:e});if(a?.running)return;if(a?.exists){i.debug(`[SidePanel] found abandoned checkpoint,auto addrestorehint card`),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}));let o=a.checkpoint,s=o.updatedAt?Be(Date.now()-o.updatedAt):``,c=r(`chatResume.taskInterrupted`,{elapsed:s?r(`chatResume.interruptedAgo`,{duration:s}):``});if(t){let e=C.messageHistory.find(e=>e.resumable);if(e&&(e.content=c,$C()),n){let e=n.querySelector(`.message[data-resumable]:not([data-resumable="false"])`);if(!e){let t=n.querySelectorAll(`.message.assistant`);for(let n of t)if((n.textContent||``).includes(`任务执行被中断`)){e=n;break}}e&&e.remove()}}let{element:l,messageId:u}=Aw(`assistant`,c,!0,[],null,!1,null,null,[],!0);t||(C.messageHistory.push({role:`assistant`,content:c,executionLog:[],messageId:u,resumable:!0,interrupted:!0}),$C()),rS(l,e)}}catch(e){i.warn(`[SidePanel] check abandoned checkpoint failed:`,e.message)}}async function oS(e,t=``){if(!e)return i.warn(`[SidePanel] resumeTask: missing sessionId`),!1;if(C.activeSessionId!==e)return i.warn(`[SidePanel] resumeTask: currently activesessionwith targetsession not consistent,please switch firstto targetsession`),!1;if(C.pendingCallApiSessionIds&&C.pendingCallApiSessionIds.has(e))return i.warn(`[SidePanel] resumeTask: currentsession has ongoingtask`),!1;i.debug(`[SidePanel] resumeTask: startrestoretask, sessionId:`,e,`userGuidance:`,t?`"${t.substring(0,50)}..."`:`( no )`);try{let t=await chrome.runtime.sendMessage({type:`GET_CHECKPOINT`,sessionId:e});if(!t?.exists){i.warn(`[SidePanel] resumeTask: checkpoint not found, no way to restore, sessionId:`,e);let t=r(`chatResume.checkpointNotFound`),{messageId:n}=Aw(`assistant`,t,!0,[]);return C.messageHistory.push({role:`assistant`,content:t,executionLog:[],messageId:n,resumable:!1,resumed:!0}),$C(),nS(e),!1}i.debug(`[SidePanel] resumeTask: checkpoint verified, iteration:`,t.checkpoint?.iteration)}catch(e){i.warn(`[SidePanel] resumeTask: verify checkpoint hourcommunication failed,continue tryrestore:`,e.message)}let n=e,a=Iw();C.isGenerating=!0;let o=``,s=[],c=null,l=!1,u=!1,d=!1,f=null,p=null;try{let e=await Gw(null,null,!1,{},{resumeFromCheckpoint:!0,userGuidance:t,loadingId:a});o=e.content,s=e.executionLog||[],c=e.reflectionScore,l=e.wasRevised||!1,u=e.wasStreamed||!1,f=e.streamingHtml||null,e.streamingConnected!==void 0&&e.streamingConnected,p=e.streamingMsgId||null,d=e.budgetEnded===!0}catch(e){if(C.activeSessionId!==n){let t=e.message===r(`chatMsg.errTaskStopped`),i=!!e.checkpoint||e.swRestarted||t;return t?_i(n,{role:`assistant`,content:r(`chatResume.taskCancelled`),executionLog:e.executionLog||[],resumable:i,resumed:!0}):e.swRestarted?_i(n,{role:`assistant`,content:r(`chatResume.swRestarted`),executionLog:e.executionLog||[],resumable:i,resumed:!0}):_i(n,{role:`assistant`,content:r(`chatResume.resumeFailed`,{message:e.message||r(`chatResume.unknownError`)}),executionLog:e.executionLog||[],resumable:!1,resumed:!0}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:n}})),Lw(a),!1}if(e.message===r(`chatMsg.errTaskStopped`)){Lw(a);let{messageId:t}=Aw(`assistant`,r(`chatResume.taskCancelled`),!1,e.executionLog||[]);return C.messageHistory.push({role:`assistant`,content:r(`chatResume.taskCancelled`),executionLog:e.executionLog||[],messageId:t,resumable:!0,resumed:!0}),$C(),!1}if(e.swRestarted){Lw(a);let t=!!e.checkpoint,{messageId:n}=Aw(`assistant`,r(`chatResume.swRestarted`),!1,e.executionLog||[]);return C.messageHistory.push({role:`assistant`,content:r(`chatResume.swRestarted`),executionLog:e.executionLog||[],messageId:n,resumable:t,resumed:!0}),$C(),!1}Lw(a);let t=r(`chatResume.resumeFailed`,{message:e.message||r(`chatResume.unknownError`)}),{element:i,messageId:o}=Aw(`assistant`,t,!0,e.executionLog||[]);return C.messageHistory.push({role:`assistant`,content:t,executionLog:e.executionLog||[],messageId:o,resumable:!1,resumed:!0}),$C(),!1}finally{jl(n)}nS(n);let m=d?`budget`:!1;if(C.activeSessionId!==n){let e={role:`assistant`,content:o,executionLog:s,reflectionScore:c,wasRevised:l,resumable:m,resumed:!0};return u&&f&&(e.htmlContent=f),_i(n,e),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:n}})),Lw(a),!0}if(u&&f){let e=p;return C.messageHistory.push({role:`assistant`,content:o,executionLog:s,reflectionScore:c,wasRevised:l,resumable:m,messageId:e,resumed:!0,htmlContent:f}),$C(),m&&iS(e?document.querySelector(`[data-message-id="${e}"]`):null,m),!0}Lw(a);let{element:h,messageId:g}=Aw(`assistant`,o,!0,s,c,l,null,null,[],m);return C.messageHistory.push({role:`assistant`,content:o,executionLog:s,reflectionScore:c,wasRevised:l,resumable:m,messageId:g,resumed:!0}),$C(),h&&ct(h),!0}var sS=300*1024,cS=typeof TextEncoder<`u`?new TextEncoder:null;function lS(e){return e?cS?cS.encode(e).length:e.length*3:0}var uS=`streamSnap|`,dS=e=>`${uS}${e}`,fS=new Map,pS=null;function mS(){return typeof chrome<`u`&&chrome.storage&&chrome.storage.session&&typeof chrome.storage.session.set==`function`}function hS(){if(pS||typeof window>`u`||!window.addEventListener||typeof document>`u`||!document.addEventListener)return;let e=()=>{yS()},t=()=>{document.visibilityState===`hidden`&&e()};pS={pagehide:e,onVisibility:t},window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,t)}function gS(e,t,n){if(!e||!t||typeof n!=`function`||!mS())return;hS();let r=fS.get(e)||{};r.callId!==t&&(r.oversizeLogged=!1),r.callId=t,r.read=n,r.timer||=setTimeout(()=>{let t=fS.get(e);t&&(t.timer=null,_S(e).catch(()=>{}))},700),fS.set(e,r)}async function _S(e){let t=fS.get(e);if(!t||(t.timer&&=(clearTimeout(t.timer),null),!mS()))return;let n;try{n=t.read()||{}}catch(e){i.debug(`[StreamSnapshot] 读取气泡内容失败(忽略):`,e?.message||e);return}let r=typeof n.html==`string`?n.html:``,a=typeof n.accumulated==`string`?n.accumulated:``,o=r,s=lS(r);s>307200&&(t.oversizeLogged||(t.oversizeLogged=!0,i.debug(`[StreamSnapshot] 快照 HTML ${s} 字节超过上限 ${sS},本次只存正文(接管后看不到工具卡片等富结构)`)),o=``);let c=`${o.length}|${a.length}|${o.slice(0,48)}|${o.slice(-48)}|${a.slice(-32)}`,l=Date.now();t.lastSig===c&&l-(t.lastWrittenAt||0)<3e4||(await chrome.storage.session.set({[dS(e)]:{sessionId:e,callId:t.callId,html:o,accumulated:a,ts:Date.now()}}),t.lastSig=c,t.lastWrittenAt=l)}function vS(e){let t=fS.get(e);t&&(t.timer&&clearTimeout(t.timer),fS.delete(e))}function yS(){return Promise.all([...fS.keys()].map(e=>_S(e).catch(e=>{i.debug(`[StreamSnapshot] 卸载前刷盘失败(忽略):`,e?.message||e)})))}async function bS(e){if(!e||!mS())return null;try{let t=await chrome.storage.session.get(dS(e)),n=t&&t[dS(e)];return!n||!n.callId?null:Date.now()-(n.ts||0)>18e5?(await xS(e),null):n}catch(e){return i.debug(`[StreamSnapshot] 读取快照失败(忽略):`,e?.message||e),null}}async function xS(e){let t=fS.get(e);if(t&&t.timer&&clearTimeout(t.timer),fS.delete(e),mS())try{await chrome.storage.session.remove(dS(e))}catch(e){i.debug(`[StreamSnapshot] 清除快照失败(忽略):`,e?.message||e)}}var SS=t({addStreamingMessage:()=>aC,appendThinkingIndicator:()=>lC,appendToolCallItems:()=>CC,appendToolResult:()=>PC,applyStreamSnapshot:()=>sC,attachAgentStreamChunk:()=>MC,autoScrollToBottom:()=>AS,bindProcessHeaderClick:()=>IS,cancelStreamingTask:()=>LC,createAgentStreamOutput:()=>TC,createCodeBlockHtml:()=>wC,createPreSelectCard:()=>FC,createStreamingElementAccessor:()=>GS,deleteStreamingState:()=>KS,finalizeCancelledStream:()=>RC,finalizeStreamingMessage:()=>IC,flushPendingAgentStreams:()=>NC,getPendingPreselectLog:()=>YS,getProcessStartTime:()=>$S,getReasoningContent:()=>tC,getStreamedContent:()=>qS,getThinkingStartTime:()=>ZS,initScrollToBottomBtn:()=>NS,markStreamingRetrying:()=>cC,mountStreamingElement:()=>dC,notifyNonStreamContentArrived:()=>PS,reconnectStreamingElement:()=>fC,refreshAgentNames:()=>LS,registerAgentStreamStore:()=>DC,renderStreamingContentFull:()=>xC,resetScrollState:()=>MS,resolveToolCallCard:()=>kC,scrollStreamingToBottom:()=>jS,setPendingPreselectLog:()=>XS,setProcessStartTime:()=>eC,setReasoningContent:()=>nC,setStreamedContent:()=>JS,setThinkingStartTime:()=>QS,updateScrollButtonState:()=>OS,updateStreamingMessage:()=>SC});n(`zh`,{chatStream:{thinking:`思考中...`,outputting:`输出中...`,retrying:`连接异常,正在重试 ({attempt}/{max})...`,stopGenerating:`停止生成`,thinkingResult:`思考结果`,toolActionOperate:`操作`,toolActionUpload:`上传`,toolActionDownload:`下载`,toolActionRequest:`请求`,toolActionInteract:`交互`,toolActionFill:`填写`,toolActionDispatch:`分派`,toolActionPreview:`预览`,toolActionRead:`读取`,toolActionWrite:`写入`,terminateCommand:`终止命令`,abortWaiting:`终止等待(跳过当前工具执行等待,不终止实际进程)`,executing:`执行中...`,terminating:`正在终止...`,copyCode:`复制代码`,truncatedTitle:`原始结果过大,已截断显示`,truncatedNote:`(输出过长已截断)`,noOutput:`(无输出)`,execFailed:`执行失败`,clickToExpand:`
|
|
1589
1589
|
... (点击展开查看完整输出)`,execResult:`执行结果`,statusFailed:`失败`,statusCompleted:`完成`,preselectFiltered:`从 {total} 个工具中筛选出 <strong>{count}</strong> 个:`,preselectSkippedAll:`跳过筛选({reason}),使用全部工具`,preselectSkippedCount:`跳过筛选({reason}),工具总数 {count}`,preselectDirectAnswer:`模型直接回答:`,toolPreselect:`工具预筛选`,toolsAfterFilter:`筛选后工具数:<strong>{count}</strong>`,listSeparator:`、`,totalNodes:`总节点`,successLabel:`成功`,failedLabel:`失败`,tokenLabel:`Token`,tokenUsageTitle:`Token 消耗: {total} (Prompt: {prompt}, Completion: {completion})`,thinkingProcess:`思考过程`,copyMarkdown:`复制 Markdown 内容 (Ctrl/Cmd + 点击复制富文本)`,copy:`复制`,quoteTitle:`引用该内容问答`,quote:`引用`,export:`导出`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,executionLog:`执行日志`,reflectionRoundsTag:` ({count}轮)`,qualityAssessmentTitle:`AI 质量评估: {score}/10{rounds}
|
|
1590
1590
|
点击查看评估详情`,reflectionFailedTitle:`反思评估失败(点击查看执行日志)`,reflectionFailedBadge:`⚠️ 反思失败`,prototypeOpenedLocal:`已在本地浏览器打开,点击可在面板内查看`,viewUiPrototype:`查看 UI 原型`,bookmarkMessage:`收藏消息`,removeBookmark:`取消收藏`,forkSession:`从此处分叉会话(仅复制到此条消息)`,deleteMessage:`删除消息`,stopping:`停止中...`,taskStopped:`任务已被用户停止`,cancelled:`已取消`}}),n(`en`,{chatStream:{thinking:`Thinking...`,outputting:`Outputting...`,retrying:`Connection unstable, retrying ({attempt}/{max})...`,stopGenerating:`Stop generating`,thinkingResult:`Thinking result`,toolActionOperate:`Operate`,toolActionUpload:`Upload`,toolActionDownload:`Download`,toolActionRequest:`Request`,toolActionInteract:`Interact`,toolActionFill:`Fill`,toolActionDispatch:`Dispatch`,toolActionPreview:`Preview`,toolActionRead:`Read`,toolActionWrite:`Write`,terminateCommand:`Terminate command`,abortWaiting:`Abort waiting (skip current tool wait, does not terminate the actual process)`,executing:`Executing...`,terminating:`Terminating...`,copyCode:`Copy code`,truncatedTitle:`Original result too large, truncated for display`,truncatedNote:`(output too long, truncated)`,noOutput:`(no output)`,execFailed:`Execution failed`,clickToExpand:`
|
|
1591
1591
|
... (click to expand and view full output)`,execResult:`Execution result`,statusFailed:`Failed`,statusCompleted:`Completed`,preselectFiltered:`Filtered <strong>{count}</strong> of {total} tools: `,preselectSkippedAll:`Skipped filtering ({reason}), using all tools`,preselectSkippedCount:`Skipped filtering ({reason}), total tools: {count}`,preselectDirectAnswer:`Model direct answer: `,toolPreselect:`Tool Pre-filter`,toolsAfterFilter:`Tools after filtering: <strong>{count}</strong>`,listSeparator:`, `,totalNodes:`Total nodes`,successLabel:`Success`,failedLabel:`Failed`,tokenLabel:`Token`,tokenUsageTitle:`Token usage: {total} (Prompt: {prompt}, Completion: {completion})`,thinkingProcess:`Thinking process`,copyMarkdown:`Copy Markdown content (Ctrl/Cmd + click to copy rich text)`,copy:`Copy`,quoteTitle:`Quote this content for Q&A`,quote:`Quote`,export:`Export`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,executionLog:`Execution log`,reflectionRoundsTag:` ({count} rounds)`,qualityAssessmentTitle:`AI quality assessment: {score}/10{rounds}
|
|
1592
|
-
Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection failed`,prototypeOpenedLocal:`Already opened in local browser, click to view in panel`,viewUiPrototype:`View UI prototype`,bookmarkMessage:`Bookmark message`,removeBookmark:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessage:`Delete message`,stopping:`Stopping...`,taskStopped:`Task stopped by user`,cancelled:`Cancelled`}});var CS=new Map,wS=!1,TS=!1,ES=!1,DS=!1;function OS(){let e=document.getElementById(`scrollToBottomBtn`),t=document.getElementById(`scrollToBottomBadge`);if(!e)return;let n=document.getElementById(`chatContainer`);if(!n)return;let r=n.scrollHeight-n.scrollTop-n.clientHeight<80;r?(e.classList.remove(`visible`),DS=!1):e.classList.add(`visible`),t&&(DS&&!r?(t.classList.add(`active`),C.isGenerating?t.classList.add(`pulsing`):t.classList.remove(`pulsing`)):t.classList.remove(`active`,`pulsing`))}function kS(){if(ES)return;let e=document.getElementById(`chatContainer`);e&&(ES=!0,e.addEventListener(`scroll`,()=>{if(wS)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;TS=!t,t?DS=!1:C.isGenerating&&(DS=!0),OS()},{passive:!0}),document.addEventListener(`generating-state-changed`,()=>{C.isGenerating&&(DS=!0),requestAnimationFrame(()=>OS())}))}function AS(e,t={}){if(!e)return;kS();let{force:n=!1,smooth:r=!1}=t;if(!n&&TS){DS=!0,OS();return}if(wS=!0,r){e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),requestAnimationFrame(()=>{wS=!1});return}e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{TS||(e.scrollTop=e.scrollHeight),requestAnimationFrame(()=>{wS=!1})})}function jS(e){if(!e||!e.isConnected)return;let t=document.getElementById(`chatContainer`);t&&AS(t)}function MS(){TS=!1,DS=!1,C.isGenerating&&(DS=!0),OS()}function NS(){kS();let e=document.getElementById(`scrollToBottomBtn`);if(!e||e.dataset.bound)return;e.dataset.bound=`1`;let t=localStorage.getItem(`scrollBtnPosition`)||`center`;e.classList.add(`pos-${t}`);let n=!1,r=0,i=0,a=!1,o=0,s=!1;function c(){let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.clientWidth,r={left:n/6,center:n/2,right:n*5/6},i=`center`,a=1/0;for(let[e,t]of Object.entries(r)){let n=Math.abs(o-t);n<a&&(a=n,i=e)}e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.classList.add(`pos-${i}`),e.style.left=``,e.style.marginLeft=``,e.style.right=``,localStorage.setItem(`scrollBtnPosition`,i)}function l(){let t=document.getElementById(`chatContainer`),n=e.getBoundingClientRect(),a=t?t.getBoundingClientRect():null,o=a?n.left-a.left+n.width/2:r;e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.style.left=`${o}px`,e.style.marginLeft=`0`,e.style.right=`auto`,e.classList.add(`dragging`),i=o,s=!0}function u(e){e.type===`mousedown`&&e.button!==0||(e.preventDefault(),n=!0,a=!1,s=!1,r=e.touches?e.touches[0].clientX:e.clientX)}function d(t){if(!n)return;let c=t.touches?t.touches[0].clientX:t.clientX;if(!s){if(Math.abs(c-r)<=3)return;a=!0,l()}let u=document.getElementById(`chatContainer`);if(!u)return;let d=u.getBoundingClientRect(),f=i+(c-r),p=e.offsetWidth/2;f=Math.max(p,Math.min(d.width-p,f)),o=f,e.style.left=`${f}px`}function f(){if(n){if(n=!1,a)e.classList.remove(`dragging`),c();else{s&&(e.classList.remove(`dragging`),e.style.left=``,e.style.marginLeft=``,e.style.right=``);let t=document.getElementById(`chatContainer`);t&&(TS=!1,DS=!1,OS(),AS(t,{force:!0,smooth:!0}))}a=!1,s=!1}}e.addEventListener(`mousedown`,u),e.addEventListener(`touchstart`,u,{passive:!1}),document.addEventListener(`mousemove`,d),document.addEventListener(`touchmove`,d,{passive:!1}),document.addEventListener(`mouseup`,f),document.addEventListener(`touchend`,f),OS()}function PS(){kS();let e=document.getElementById(`chatContainer`);e&&(e.scrollHeight-e.scrollTop-e.clientHeight<80||(DS=!0),OS())}function FS(e,t){let n=e.querySelector(`.thinking-process-content`);if(!n)return;e.dataset.activeFilter=t,e.querySelectorAll(`.thinking-process-stat[data-filter]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===t)});let r=e=>t===`all`||e===t;n.querySelectorAll(`.tool-call-item`).forEach(e=>{e.classList.contains(`preselect-card`)||(e.style.display=r(e.dataset.status)?``:`none`)}),n.querySelectorAll(`.thinking-badge`).forEach(e=>{let t=r(e.dataset.status||`success`);e.style.display=t?``:`none`;let n=e.nextElementSibling;n&&n.classList.contains(`thinking-content`)&&(n.style.display=t?``:`none`)}),n.querySelectorAll(`.thinking-content`).forEach(e=>{let t=e.previousElementSibling;t&&t.classList.contains(`thinking-badge`)||(e.style.display=r(`success`)?``:`none`)})}function IS(e){if(!e||e._filterBound)return;e._filterBound=!0;let t=[``,`success`,`failed`];e.querySelectorAll(`.thinking-process-stat`).forEach((e,n)=>{t[n]&&(e.dataset.filter=t[n],e.classList.add(`filterable`))}),e.querySelectorAll(`.token-stat`).forEach(e=>{e.style.cursor=`pointer`}),e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=t.target.closest(`.thinking-process-stat`),r=e.closest(`.thinking-process`);if(r){if(n&&n.classList.contains(`token-stat`)){let e=r.closest(`.message`);if(e)try{let t=e.dataset.executionLog,r=
|
|
1592
|
+
Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection failed`,prototypeOpenedLocal:`Already opened in local browser, click to view in panel`,viewUiPrototype:`View UI prototype`,bookmarkMessage:`Bookmark message`,removeBookmark:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessage:`Delete message`,stopping:`Stopping...`,taskStopped:`Task stopped by user`,cancelled:`Cancelled`}});var CS=new Map,wS=!1,TS=!1,ES=!1,DS=!1;function OS(){let e=document.getElementById(`scrollToBottomBtn`),t=document.getElementById(`scrollToBottomBadge`);if(!e)return;let n=document.getElementById(`chatContainer`);if(!n)return;let r=n.scrollHeight-n.scrollTop-n.clientHeight<80;r?(e.classList.remove(`visible`),DS=!1):e.classList.add(`visible`),t&&(DS&&!r?(t.classList.add(`active`),C.isGenerating?t.classList.add(`pulsing`):t.classList.remove(`pulsing`)):t.classList.remove(`active`,`pulsing`))}function kS(){if(ES)return;let e=document.getElementById(`chatContainer`);e&&(ES=!0,e.addEventListener(`scroll`,()=>{if(wS)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;TS=!t,t?DS=!1:C.isGenerating&&(DS=!0),OS()},{passive:!0}),document.addEventListener(`generating-state-changed`,()=>{C.isGenerating&&(DS=!0),requestAnimationFrame(()=>OS())}))}function AS(e,t={}){if(!e)return;kS();let{force:n=!1,smooth:r=!1}=t;if(!n&&TS){DS=!0,OS();return}if(wS=!0,r){e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),requestAnimationFrame(()=>{wS=!1});return}e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{TS||(e.scrollTop=e.scrollHeight),requestAnimationFrame(()=>{wS=!1})})}function jS(e){if(!e||!e.isConnected)return;let t=document.getElementById(`chatContainer`);t&&AS(t)}function MS(){TS=!1,DS=!1,C.isGenerating&&(DS=!0),OS()}function NS(){kS();let e=document.getElementById(`scrollToBottomBtn`);if(!e||e.dataset.bound)return;e.dataset.bound=`1`;let t=localStorage.getItem(`scrollBtnPosition`)||`center`;e.classList.add(`pos-${t}`);let n=!1,r=0,i=0,a=!1,o=0,s=!1;function c(){let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.clientWidth,r={left:n/6,center:n/2,right:n*5/6},i=`center`,a=1/0;for(let[e,t]of Object.entries(r)){let n=Math.abs(o-t);n<a&&(a=n,i=e)}e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.classList.add(`pos-${i}`),e.style.left=``,e.style.marginLeft=``,e.style.right=``,localStorage.setItem(`scrollBtnPosition`,i)}function l(){let t=document.getElementById(`chatContainer`),n=e.getBoundingClientRect(),a=t?t.getBoundingClientRect():null,o=a?n.left-a.left+n.width/2:r;e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.style.left=`${o}px`,e.style.marginLeft=`0`,e.style.right=`auto`,e.classList.add(`dragging`),i=o,s=!0}function u(e){e.type===`mousedown`&&e.button!==0||(e.preventDefault(),n=!0,a=!1,s=!1,r=e.touches?e.touches[0].clientX:e.clientX)}function d(t){if(!n)return;let c=t.touches?t.touches[0].clientX:t.clientX;if(!s){if(Math.abs(c-r)<=3)return;a=!0,l()}let u=document.getElementById(`chatContainer`);if(!u)return;let d=u.getBoundingClientRect(),f=i+(c-r),p=e.offsetWidth/2;f=Math.max(p,Math.min(d.width-p,f)),o=f,e.style.left=`${f}px`}function f(){if(n){if(n=!1,a)e.classList.remove(`dragging`),c();else{s&&(e.classList.remove(`dragging`),e.style.left=``,e.style.marginLeft=``,e.style.right=``);let t=document.getElementById(`chatContainer`);t&&(TS=!1,DS=!1,OS(),AS(t,{force:!0,smooth:!0}))}a=!1,s=!1}}e.addEventListener(`mousedown`,u),e.addEventListener(`touchstart`,u,{passive:!1}),document.addEventListener(`mousemove`,d),document.addEventListener(`touchmove`,d,{passive:!1}),document.addEventListener(`mouseup`,f),document.addEventListener(`touchend`,f),OS()}function PS(){kS();let e=document.getElementById(`chatContainer`);e&&(e.scrollHeight-e.scrollTop-e.clientHeight<80||(DS=!0),OS())}function FS(e,t){let n=e.querySelector(`.thinking-process-content`);if(!n)return;e.dataset.activeFilter=t,e.querySelectorAll(`.thinking-process-stat[data-filter]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===t)});let r=e=>t===`all`||e===t;n.querySelectorAll(`.tool-call-item`).forEach(e=>{e.classList.contains(`preselect-card`)||(e.style.display=r(e.dataset.status)?``:`none`)}),n.querySelectorAll(`.thinking-badge`).forEach(e=>{let t=r(e.dataset.status||`success`);e.style.display=t?``:`none`;let n=e.nextElementSibling;n&&n.classList.contains(`thinking-content`)&&(n.style.display=t?``:`none`)}),n.querySelectorAll(`.thinking-content`).forEach(e=>{let t=e.previousElementSibling;t&&t.classList.contains(`thinking-badge`)||(e.style.display=r(`success`)?``:`none`)})}function IS(e){if(!e||e._filterBound)return;e._filterBound=!0;let t=[``,`success`,`failed`];e.querySelectorAll(`.thinking-process-stat`).forEach((e,n)=>{t[n]&&(e.dataset.filter=t[n],e.classList.add(`filterable`))}),e.querySelectorAll(`.token-stat`).forEach(e=>{e.style.cursor=`pointer`}),e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=t.target.closest(`.thinking-process-stat`),r=e.closest(`.thinking-process`);if(r){if(n&&n.classList.contains(`token-stat`)){let e=r.closest(`.message`);if(e)try{let t=e.dataset.executionLog,r=We(t?JSON.parse(t):[]);r&&Je(r,n)}catch{}return}n&&n.dataset.filter?FS(r,r.dataset.activeFilter===n.dataset.filter?`all`:n.dataset.filter):r.classList.toggle(`collapsed`)}});let n=e.closest(`.thinking-process`);n&&FS(n,n.dataset.activeFilter||`all`)}async function LS(){try{let{getAllAgents:e}=await A(async()=>{let{getAllAgents:e}=await import(`./agent-store-CE4-QMOA.js`).then(e=>e.t);return{getAllAgents:e}},__vite__mapDeps([0,1,2,3])),t=await e();CS.clear();for(let e of t)CS.set(e.id,e.name||e.id)}catch{}}function RS(e){return CS.get(e)||e}var zS=new Map,BS=new Map,VS=null,HS=0,US=0,WS=``;function GS(e){return t=>t===void 0?zS.get(e)||null:(zS.set(e,t),t)}function KS(e){zS.delete(e),BS.delete(e),xS(e)}function qS(e){return BS.get(e)||``}function JS(e,t){if(BS.set(e,t),!t){vS(e);return}oC(zS.get(e))}function YS(){return VS}function XS(e){VS=e}function ZS(){return HS}function QS(e){HS=e}function $S(){return US}function eC(e){US=e}function tC(){return WS}function nC(e){WS=e}function rC(){return`
|
|
1593
1593
|
<svg class="thinking-icon pulse-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1594
1594
|
<path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/>
|
|
1595
1595
|
<circle cx="8" cy="12" r="1.5"/>
|
|
@@ -1610,9 +1610,9 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1610
1610
|
<div class="thinking-indicator">${rC()}</div>
|
|
1611
1611
|
<div class="stream-status hidden"></div>
|
|
1612
1612
|
</div>
|
|
1613
|
-
`,(!e||e===C.activeSessionId)&&t&&(t.appendChild(n),MS(),OS(),requestAnimationFrame(()=>{AS(t,{force:!0})})),iC(n),n}function oC(e){let t=e?.dataset?.sessionId,n=e?.dataset?.callId;!t||!n||gS(t,n,()=>({html:e.innerHTML,accumulated:qS(t)}))}function sC(e,t){return!e||!t?!1:(e.innerHTML=t,iC(e),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{t.ctrlKey||t.metaKey||e.closest(`.tool-call-item`)?.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`),n=t?.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),
|
|
1613
|
+
`,(!e||e===C.activeSessionId)&&t&&(t.appendChild(n),MS(),OS(),requestAnimationFrame(()=>{AS(t,{force:!0})})),iC(n),n}function oC(e){let t=e?.dataset?.sessionId,n=e?.dataset?.callId;!t||!n||gS(t,n,()=>({html:e.innerHTML,accumulated:qS(t)}))}function sC(e,t){return!e||!t?!1:(e.innerHTML=t,iC(e),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{t.ctrlKey||t.metaKey||e.closest(`.tool-call-item`)?.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`),n=t?.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),rt(),!0)}function cC(e,t,n){let i=e?.querySelector(`.thinking-indicator:not(.hidden) .thinking-label`);return i?(i.textContent=r(`chatStream.retrying`,{attempt:t,max:n}),i.dataset.retrying=`1`,!0):!1}function lC(e){let t=e?.querySelector(`.stream-content`);if(!t||e.querySelector(`.thinking-indicator:not(.hidden)`))return null;let n=document.createElement(`div`);return n.className=`thinking-indicator`,n.innerHTML=rC(),t.appendChild(n),iC(n),n}function uC(e,t,n){if(e.contains(n)){let r=n.previousElementSibling;r&&r.classList.contains(`thinking-content`)?e.insertBefore(t,r):e.insertBefore(t,n);return}let r=e.querySelectorAll(`.thinking-content`),i=r[r.length-1],a=i?i.nextElementSibling:null;i&&(!a||!a.classList.contains(`thinking-badge`))?e.insertBefore(t,i):e.appendChild(t)}function dC(e){let t=zS.get(e);if(!t||t.dataset.sessionId&&t.dataset.sessionId!==e)return!1;let n=document.getElementById(`chatContainer`);return n?(n.appendChild(t),requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight}),!0):!1}function fC(e){let t=zS.get(e);if(!t||t.dataset.sessionId&&t.dataset.sessionId!==e)return;let n=document.getElementById(`chatContainer`);if(!n)return;n.appendChild(t);let i=BS.get(e)||``;if(i){SC(t,i);let e=t.querySelector(`.stream-content`);t.querySelectorAll(`.thinking-indicator:not(.hidden)`).forEach(t=>{if(t.classList.add(`hidden`),!e)return;let n=document.createElement(`span`);n.className=`thinking-badge`,n.dataset.status=`success`,n.innerHTML=`<svg class="thinking-icon-static" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/></svg>`+r(`chatStream.thinkingResult`),uC(e,n,t)})}requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight})}var pC=new WeakMap,mC=5;function hC(e){let t=e.querySelector(`.stream-content`);if(!t)return null;let n=t.querySelector(`.thinking-indicator:not(.hidden)`)||e.querySelector(`.thinking-indicator:not(.hidden)`);if(n){if(t.contains(n)){let e=n.previousElementSibling;if(e&&e.classList.contains(`thinking-content`))return e;let r=document.createElement(`div`);return r.className=`thinking-content`,t.insertBefore(r,n),r}let e=t.querySelectorAll(`.thinking-content`);if(e.length===0){let e=document.createElement(`div`);return e.className=`thinking-content`,t.appendChild(e),e}let r=e[e.length-1],i=r.nextElementSibling;if(!i||!i.classList.contains(`thinking-badge`))return r;let a=document.createElement(`div`);return a.className=`thinking-content`,t.appendChild(a),a}let r=t.querySelectorAll(`.thinking-badge`);if(r.length>0){let e=r[r.length-1],t=e.nextElementSibling;if(t&&t.classList.contains(`thinking-content`))return t;let n=document.createElement(`div`);return n.className=`thinking-content`,e.after(n),n}let i=document.createElement(`div`);return i.className=`thinking-content`,t.appendChild(i),i}function gC(e){let t=e.trim();return t?!!(/^(```|~~~)/.test(t)||/^([-*+]|\d+[.)])\s/.test(t)||/^>/.test(t)||/^\|/.test(t)||/^\s{2,}\S/.test(e)||t.startsWith(`<`)||/^\[[^\]]+\]:/.test(t)):!1}function _C(e,t){let n=t,r=!1,i=t,a=``;for(;n<=e.length;){let t=e.indexOf(`
|
|
1614
1614
|
`,n),o=t===-1?e.length:t,s=e.slice(n,o),c=s.trim(),l=c.startsWith("```")||c.startsWith(`~~~`);if(l&&(r=!r),!r&&!l&&c===``){let n=``,r=t===-1?e.length:t+1;for(let t=0;t<mC&&r<e.length;t++){let t=e.indexOf(`
|
|
1615
|
-
`,r),i=t===-1?e.length:t,a=e.slice(r,i);if(a.trim()){n=a;break}if(r=i+1,t===-1)break}n&&!gC(n)&&!gC(a)&&(i=t+1)}if(c&&(a=s),t===-1)break;n=t+1}return i}function vC(e){let t=document.createElement(`template`);return t.innerHTML=e,t.content}function yC(e,t){e.innerHTML=``;let n=document.createElement(`div`);n.className=`markdown-body`,e.appendChild(n);let r=_C(t,0);r>0&&n.appendChild(vC(et(t.slice(0,r))));let i=null,a=t.slice(r);if(a){let e=vC(et(a));i=e.firstChild,n.appendChild(e)}pC.set(e,{content:t,renderedChars:r,firstTailNode:i,body:n})}function bC(e,t){let n=t||``,r=pC.get(e);if(!r||!n.startsWith(r.content)){yC(e,n);return}let i=r.body;if(!i||i.parentNode!==e){yC(e,n);return}let a=r.firstTailNode;for(;a;){let e=a.nextSibling;a.remove(),a=e}r.firstTailNode=null;let o=_C(n,r.renderedChars);o>r.renderedChars&&(i.appendChild(vC(et(n.slice(r.renderedChars,o)))),r.renderedChars=o);let s=n.slice(r.renderedChars);if(s){let e=vC(et(s));r.firstTailNode=e.firstChild,i.appendChild(e)}r.content=n}function xC(e,t){if(!e||!t)return;let n=hC(e);n&&yC(n,t)}function SC(e,t){let n=e.querySelector(`.stream-content`);if(!n)return;let i=n.querySelector(`.thinking-indicator:not(.hidden)`)||e.querySelector(`.thinking-indicator:not(.hidden)`);if(i){let e=i.querySelector(`.thinking-label`);e&&(e.textContent===r(`chatStream.thinking`)||e.dataset.retrying===`1`)&&(e.textContent=r(`chatStream.outputting`),delete e.dataset.retrying)}let a=hC(e);a&&bC(a,t),oC(e),e.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&AS(e)})}function CC(e,t){if(!e||!t?.length)return;let n=e.querySelector(`.stream-content`);if(!n)return;let i=e.querySelector(`.thinking-indicator:not(.hidden)`);if(i){let e=HS>0?
|
|
1615
|
+
`,r),i=t===-1?e.length:t,a=e.slice(r,i);if(a.trim()){n=a;break}if(r=i+1,t===-1)break}n&&!gC(n)&&!gC(a)&&(i=t+1)}if(c&&(a=s),t===-1)break;n=t+1}return i}function vC(e){let t=document.createElement(`template`);return t.innerHTML=e,t.content}function yC(e,t){e.innerHTML=``;let n=document.createElement(`div`);n.className=`markdown-body`,e.appendChild(n);let r=_C(t,0);r>0&&n.appendChild(vC(et(t.slice(0,r))));let i=null,a=t.slice(r);if(a){let e=vC(et(a));i=e.firstChild,n.appendChild(e)}pC.set(e,{content:t,renderedChars:r,firstTailNode:i,body:n})}function bC(e,t){let n=t||``,r=pC.get(e);if(!r||!n.startsWith(r.content)){yC(e,n);return}let i=r.body;if(!i||i.parentNode!==e){yC(e,n);return}let a=r.firstTailNode;for(;a;){let e=a.nextSibling;a.remove(),a=e}r.firstTailNode=null;let o=_C(n,r.renderedChars);o>r.renderedChars&&(i.appendChild(vC(et(n.slice(r.renderedChars,o)))),r.renderedChars=o);let s=n.slice(r.renderedChars);if(s){let e=vC(et(s));r.firstTailNode=e.firstChild,i.appendChild(e)}r.content=n}function xC(e,t){if(!e||!t)return;let n=hC(e);n&&yC(n,t)}function SC(e,t){let n=e.querySelector(`.stream-content`);if(!n)return;let i=n.querySelector(`.thinking-indicator:not(.hidden)`)||e.querySelector(`.thinking-indicator:not(.hidden)`);if(i){let e=i.querySelector(`.thinking-label`);e&&(e.textContent===r(`chatStream.thinking`)||e.dataset.retrying===`1`)&&(e.textContent=r(`chatStream.outputting`),delete e.dataset.retrying)}let a=hC(e);a&&bC(a,t),oC(e),e.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&AS(e)})}function CC(e,t){if(!e||!t?.length)return;let n=e.querySelector(`.stream-content`);if(!n)return;let i=e.querySelector(`.thinking-indicator:not(.hidden)`);if(i){let e=HS>0?Be(Date.now()-HS):``,t=document.createElement(`span`);t.className=`thinking-badge`,t.innerHTML=`<svg class="thinking-icon-static" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/></svg>${r(`chatStream.thinkingResult`)}${e?` <span class="thinking-duration">`+e+`</span>`:``}`,t.dataset.status=`success`,uC(n,t,i),i.classList.add(`hidden`),n.contains(i)||i.remove()}let a={execute_command:{metaType:`exec`},agent_exec:{metaType:`exec`},agent_file:{metaType:`file`,action:r(`chatStream.toolActionOperate`)},file_upload:{metaType:`file`,action:r(`chatStream.toolActionUpload`)},download_file:{metaType:`file`,action:r(`chatStream.toolActionDownload`)},fetch_url:{metaType:`web`,action:r(`chatStream.toolActionRequest`)},interact_element:{metaType:`web`,action:r(`chatStream.toolActionInteract`)},fill_form:{metaType:`web`,action:r(`chatStream.toolActionFill`)},manage_tab:{metaType:`web`,action:r(`chatStream.toolActionOperate`)},search_browser_data:{metaType:`search`},search_in_page:{metaType:`search`},dispatch_task:{metaType:`subagent`,action:r(`chatStream.toolActionDispatch`)},exec_log:{metaType:`search`},preview_ui:{metaType:`web`,action:r(`chatStream.toolActionPreview`)}};t.filter(e=>e&&typeof e==`object`).forEach(e=>{let t=e.function?.name||`unknown`,i=a[t]||{metaType:`other`},o;try{o=JSON.parse(e.function?.arguments||`{}`)}catch{o={raw:e.function?.arguments||``}}let s=JSON.stringify(o,null,2),c=``,l=``;if(i.metaType===`exec`){let e=o.command||o.cmd||JSON.stringify(o);l=e,c=`<code class="tool-call-cmd">$ ${I(e)}</code>`}else if(i.metaType===`file`){let e=o.file_path||o.filePath||o.path||o.filename||o.fileName||o.url||``,n=i.action===r(`chatStream.toolActionRead`)?`📖`:i.action===r(`chatStream.toolActionWrite`)?`📝`:i.action===r(`chatStream.toolActionUpload`)?`📤`:`📥`;l=e||t,c=`<span class="tool-call-file">${n} ${I(e)||I(t)}</span>`}else if(i.metaType===`web`){let e=o.url||o.href||o.selector||``;l=e||JSON.stringify(o),c=`<span class="tool-call-web">${I(i.action)}: ${I(e)||I(JSON.stringify(o).substring(0,80))}</span>`}else if(i.metaType===`search`){let e=o.query||o.keyword||o.text||``;l=e||t,c=`<span class="tool-call-search">🔍 ${I(e)||I(t)}</span>`}else if(i.metaType===`subagent`){let e=o.subAgentId||o.agent_id||``,t=e?RS(e):``,n=(o.task||``).substring(0,80);t&&t!==e?(l=`${t} (${e}): ${n}`,c=`<span class="tool-call-subagent">🤖 <strong>${I(t)}</strong> <span class="tool-call-subagent-id">(${I(e)})</span>: ${I(n)}</span>`):(l=`${e}: ${n}`,c=`<span class="tool-call-subagent">🤖 <strong>${I(e)}</strong>: ${I(n)}</span>`)}else{let e=Object.keys(o);if(e.length===0)l=t,c=`<span>${I(t)}</span>`;else if(e.length===1){let t=JSON.stringify(o[e[0]]);l=`${e[0]}: ${t}`,c=`<span>${I(e[0])}: ${I(t.substring(0,80))}</span>`}else l=e.map(e=>`${e}=${JSON.stringify(o[e])}`).join(`, `),c=`<span>${e.slice(0,2).map(e=>`${I(e)}=${I(JSON.stringify(o[e]).substring(0,30))}`).join(`, `)}${e.length>2?` ...`:``}</span>`}let u=i.metaType===`exec`?`<svg class="tool-call-icon exec" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1616
1616
|
<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>
|
|
1617
1617
|
</svg>`:i.metaType===`file`?`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1618
1618
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
@@ -1632,7 +1632,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1632
1632
|
</button>`;if(d.innerHTML=`
|
|
1633
1633
|
<div class="tool-call-header">
|
|
1634
1634
|
${u}
|
|
1635
|
-
<span class="tool-call-name">${
|
|
1635
|
+
<span class="tool-call-name">${I(t)}</span>
|
|
1636
1636
|
<div class="tool-call-summary">${c}</div>
|
|
1637
1637
|
<span class="tool-call-executing">${r(`chatStream.executing`)}</span>
|
|
1638
1638
|
${p}
|
|
@@ -1640,9 +1640,9 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1640
1640
|
<svg class="tool-call-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
|
|
1641
1641
|
</div>
|
|
1642
1642
|
<div class="tool-call-body">
|
|
1643
|
-
${wC(
|
|
1643
|
+
${wC(I(s))}
|
|
1644
1644
|
</div>
|
|
1645
|
-
`,l){let e=d.querySelector(`.tool-call-summary`);e&&(e.title=l)}if(
|
|
1645
|
+
`,l){let e=d.querySelector(`.tool-call-summary`);e&&(e.title=l)}if(rt(),f){let e=d.querySelector(`.tool-call-terminate-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),Vw(C.activeSessionId)})}let h=d.querySelector(`.tool-call-abort-btn`);h&&h.addEventListener(`click`,e=>{e.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:C.activeSessionId}),h.disabled=!0,h.title=r(`chatStream.terminating`)}),d.querySelector(`.tool-call-header`).addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||d.classList.toggle(`expanded`)}),n.appendChild(d)}),NC(null,e),oC(e),e.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&AS(e)})}function wC(e,t=``){let n=t?` class="${t}"`:``;return`<div class="code-block-container" style="position: relative;">
|
|
1646
1646
|
<button class="code-copy-btn" title="${r(`chatStream.copyCode`)}">
|
|
1647
1647
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1648
1648
|
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
|
|
@@ -1653,18 +1653,18 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1653
1653
|
<div class="tool-result-title">${r(`chatMsg.toolResultTitle`)}</div>
|
|
1654
1654
|
${wC(``,`agent-stream-content`)}
|
|
1655
1655
|
`;let i=(e?e.querySelector(`.tool-call-body`)||e:null)||t;return i&&i.appendChild(n),n}var EC=new WeakMap;function DC(e,t){e&&t&&EC.set(e,t)}function OC(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(String(e)):String(e).replace(/["\\]/g,`\\$&`)}function kC(e,t){if(!t)return null;let n=`.tool-call-item[data-tool-call-id="${OC(t)}"]`,r=e&&typeof e.querySelector==`function`?e.querySelector(n):null;if(r)return r;if(typeof document>`u`)return null;let i=document.querySelectorAll(n);return i.length?i[i.length-1]:null}function AC(e){let t=e.querySelector(`.agent-stream-output`),n=t?t.querySelector(`code`):null;if(t&&n)return{element:t,codeEl:n};let r=TC(e,null);return{element:r,codeEl:r.querySelector(`code`)}}function jC(e,t,n){let r=e.codeEl;if(!r||!n)return;let i=document.createTextNode(n);if(t===`stderr`){if(!e.stderrSeparator){let t=document.createTextNode(`
|
|
1656
|
-
`);r.appendChild(t),e.stderrSeparator=t}r.appendChild(i)}else e.stderrSeparator?r.insertBefore(i,e.stderrSeparator):r.appendChild(i)}function MC(e,t,n){if(!e||!n||!n.execId)return null;let r=typeof e.get==`function`?e.get(n.execId):e[n.execId];if(!r){let i=kC(t,n.toolCallId);if(i){let{element:e,codeEl:t}=AC(i);r={element:e,codeEl:t,stderrSeparator:null,toolCallId:n.toolCallId||``,pending:null},
|
|
1656
|
+
`);r.appendChild(t),e.stderrSeparator=t}r.appendChild(i)}else e.stderrSeparator?r.insertBefore(i,e.stderrSeparator):r.appendChild(i)}function MC(e,t,n){if(!e||!n||!n.execId)return null;let r=typeof e.get==`function`?e.get(n.execId):e[n.execId];if(!r){let i=kC(t,n.toolCallId);if(i){let{element:e,codeEl:t}=AC(i);r={element:e,codeEl:t,stderrSeparator:null,toolCallId:n.toolCallId||``,pending:null},rt()}else if(n.toolCallId)r={element:null,codeEl:null,stderrSeparator:null,toolCallId:n.toolCallId,pending:{stdout:``,stderr:``}};else{let e=TC(null,t?t.querySelector(`.stream-content`):null);r={element:e,codeEl:e.querySelector(`code`),stderrSeparator:null,toolCallId:``,pending:null},rt()}typeof e.set==`function`?e.set(n.execId,r):e[n.execId]=r}let i=n.data||``;if(r.codeEl){jC(r,n.streamType,i);let e=r.codeEl.parentElement;e&&(e.scrollTop=e.scrollHeight)}else r.pending&&i&&(n.streamType===`stderr`?r.pending.stderr+=i:r.pending.stdout+=i);return r}function NC(e,t){let n=e||(t?EC.get(t):null);if(!n)return;let r=typeof n.values==`function`?[...n.values()]:Object.values(n);for(let e of r){if(!e||e.codeEl||!e.pending)continue;let n=kC(t,e.toolCallId);if(!n)continue;let{element:r,codeEl:i}=AC(n),{stdout:a,stderr:o}=e.pending;e.element=r,e.codeEl=i,e.stderrSeparator=null,e.pending=null,a&&jC(e,`stdout`,a),o&&jC(e,`stderr`,o);let s=i.parentElement;s&&(s.scrollTop=s.scrollHeight),rt()}}function PC(e,t){if(!e?.toolCallId)return;let n=t;if(!n)return;let i=n.querySelector(`.tool-call-item[data-tool-call-id="${e.toolCallId}"]`);if(!i)return;i.classList.add(`has-result`),i.dataset.status=e.success?`success`:`failed`,NC(null,n);let a=parseInt(i.getAttribute(`data-created-at`),10),o=Date.now()-a,s=o<400&&o>=0?400-o:0,c=()=>{let n=i.querySelector(`.tool-call-executing`);n&&n.remove();let a=i.querySelector(`.tool-call-terminate-btn`);a&&(a.style.display=`none`);let o=i.querySelector(`.tool-call-abort-btn`);o&&(o.style.display=`none`);let s=i.querySelector(`.tool-call-result`);s&&s.remove();let c=e.truncated?`<span class="tool-result-truncated" title="${r(`chatStream.truncatedTitle`)}">${r(`chatStream.truncatedNote`)}</span>`:``,l=i.getAttribute(`data-meta-type`)===`exec`,u=i.querySelector(`.tool-call-header`),d=`
|
|
1657
1657
|
<span class="tool-result-status ${e.success?`success`:`fail`}">
|
|
1658
1658
|
${e.success?`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>`:`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/></svg>`}
|
|
1659
1659
|
</span>
|
|
1660
|
-
${e.duration?`<span class="tool-result-duration">${
|
|
1660
|
+
${e.duration?`<span class="tool-result-duration">${Be(e.duration)}</span>`:``}
|
|
1661
1661
|
${c}
|
|
1662
1662
|
`,f=u.querySelector(`.tool-call-chevron`);f?f.insertAdjacentHTML(`beforebegin`,d):u.insertAdjacentHTML(`beforeend`,d);let p=i.querySelector(`.agent-stream-output code`),m=!!(p&&p.textContent.trim());if(!l||!e.success&&!m){let t=e.content||(e.success?r(`chatStream.noOutput`):r(`chatStream.execFailed`)),n=t.length>500?t.substring(0,500)+r(`chatStream.clickToExpand`):t,a=t,o=document.createElement(`div`);if(o.className=`tool-call-result`,o.innerHTML=`
|
|
1663
1663
|
<div class="tool-result-title">${r(`chatStream.execResult`)}</div>
|
|
1664
1664
|
<div class="tool-result-content">
|
|
1665
|
-
${wC(
|
|
1665
|
+
${wC(I(n))}
|
|
1666
1666
|
</div>
|
|
1667
|
-
`,a.length>500){let e=o.querySelector(`code`);e.dataset.fullContent=a;let t=!1;o.style.cursor=`pointer`,o.addEventListener(`click`,r=>{r.ctrlKey||r.metaKey||(t=!t,e.textContent=t?a:n)})}let s=i.querySelector(`.tool-call-body`);s?s.appendChild(o):i.appendChild(o)}
|
|
1667
|
+
`,a.length>500){let e=o.querySelector(`code`);e.dataset.fullContent=a;let t=!1;o.style.cursor=`pointer`,o.addEventListener(`click`,r=>{r.ctrlKey||r.metaKey||(t=!t,e.textContent=t?a:n)})}let s=i.querySelector(`.tool-call-body`);s?s.appendChild(o):i.appendChild(o)}rt(),oC(t),t.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&AS(e)})};s>0?setTimeout(c,s):c()}function FC(e){let t=document.createElement(`div`);t.className=`tool-call-item preselect-card`+(C.chatConfig?.streamExpandTools?` expanded`:``);let n=e.status===`failed`,i=``,a=``;if(e.action?.params?.selected){let t=e.action.params.selected;i=`<div class="tool-call-summary"><span>${r(`chatStream.preselectFiltered`,{total:e.apiRequest?.toolCount||`?`,count:t.length})}</span></div>`,a=`<span class="preselect-summary">${t.map(e=>`<code>${I(e)}</code>`).join(r(`chatStream.listSeparator`))}</span>`}else e.action?.name===`all_tools`?(i=`<div class="tool-call-summary"><span>${I(e.action.params.reason||``)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectSkippedAll`,{reason:I(e.action.params.reason||``)})}</span>`):e.action?.name===`skip`?(i=`<div class="tool-call-summary"><span>${I(e.action.params.reason||``)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectSkippedCount`,{reason:I(e.action.params.reason||``),count:e.action.params.toolCount||`?`})}</span>`):e.error?(i=`<div class="tool-call-summary"><span style="color:var(--danger-500);">${I(e.error)}</span></div>`,a=`<span class="preselect-summary" style="color:var(--danger-500);">${I(e.error)}</span>`):e.thought&&(i=`<div class="tool-call-summary"><span>${r(`chatStream.preselectDirectAnswer`)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectDirectAnswer`)}${I(e.thought).substring(0,200)}</span>`);let o=e.duration?Be(e.duration):``,s=n?`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/></svg>`:`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>`;return t.innerHTML=`
|
|
1668
1668
|
<div class="tool-call-header">
|
|
1669
1669
|
<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1670
1670
|
<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
|
|
@@ -1679,7 +1679,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1679
1679
|
${a}
|
|
1680
1680
|
${e.apiResponse?.toolCountAfter===void 0?``:`<div class="preselect-meta">${r(`chatStream.toolsAfterFilter`,{count:e.apiResponse.toolCountAfter})}</div>`}
|
|
1681
1681
|
</div>
|
|
1682
|
-
`,t.querySelector(`.tool-call-header`).addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||t.classList.toggle(`expanded`)}),t}function IC(e,t,n=[],a=null,o=null,s=!1){if(!e)return;e.dataset.sessionId&&xS(e.dataset.sessionId);let c=e.querySelector(`.message-content`),l=e.querySelector(`.stream-content`),u=e.querySelector(`.thinking-indicator:not(.hidden)`);if(u&&l){let e=HS>0?
|
|
1682
|
+
`,t.querySelector(`.tool-call-header`).addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||t.classList.toggle(`expanded`)}),t}function IC(e,t,n=[],a=null,o=null,s=!1){if(!e)return;e.dataset.sessionId&&xS(e.dataset.sessionId);let c=e.querySelector(`.message-content`),l=e.querySelector(`.stream-content`),u=e.querySelector(`.thinking-indicator:not(.hidden)`);if(u&&l){let e=HS>0?Be(Date.now()-HS):``,t=document.createElement(`span`);if(t.className=`thinking-badge`,t.innerHTML=`<svg class="thinking-icon-static" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/></svg>${r(`chatStream.thinkingResult`)}${e?` <span class="thinking-duration">`+e+`</span>`:``}`,t.dataset.status=`success`,l.contains(u)){let e=u.previousElementSibling;e&&e.classList.contains(`thinking-content`)?l.insertBefore(t,e):l.insertBefore(t,u),u.classList.add(`hidden`)}else{let e=l.querySelectorAll(`.thinking-content`);if(e.length>0){let n=e[e.length-1],r=n.nextElementSibling;!r||!r.classList.contains(`thinking-badge`)?l.insertBefore(t,n):l.appendChild(t)}else l.appendChild(t);u.classList.add(`hidden`),u.remove()}}e.querySelectorAll(`.thinking-indicator`).forEach(e=>e.classList.add(`hidden`));let d=e.querySelector(`.stream-status`);if(d&&d.remove(),e.classList.remove(`streaming`),c&&c.querySelector(`.tool-call-item`)||l&&l.querySelector(`.tool-call-item`)){let e=US>0?Be(Date.now()-US):``,a=(n||[]).filter(e=>e.nodeType===`api_call`||e.nodeType===`tool_exec`),o=a.filter(e=>e.status===`success`).length,u=a.filter(e=>e.status===`failed`).length,d=a.length,f=We(n),p=document.createElement(`div`);p.className=`thinking-process collapsed`;let m=document.createElement(`div`);m.className=`thinking-process-header`;let h=d>0?`
|
|
1683
1683
|
<span class="thinking-process-stat">
|
|
1684
1684
|
<span class="stat-icon node-icon">◉</span>
|
|
1685
1685
|
<span class="stat-label">${r(`chatStream.totalNodes`)}</span>
|
|
@@ -1698,10 +1698,10 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1698
1698
|
</span>
|
|
1699
1699
|
`:``,g=f?`
|
|
1700
1700
|
${d>0?`<span class="thinking-process-divider">|</span>`:``}
|
|
1701
|
-
<span class="thinking-process-stat token-stat" title="${r(`chatStream.tokenUsageTitle`,{total:
|
|
1701
|
+
<span class="thinking-process-stat token-stat" title="${r(`chatStream.tokenUsageTitle`,{total:F(f.totalTokens),prompt:F(f.promptTokens),completion:F(f.completionTokens)})}">
|
|
1702
1702
|
<span class="stat-icon token-icon">⬤</span>
|
|
1703
1703
|
<span class="stat-label">${r(`chatStream.tokenLabel`)}</span>
|
|
1704
|
-
<span class="stat-value">${
|
|
1704
|
+
<span class="stat-value">${F(f.totalTokens)}</span>
|
|
1705
1705
|
</span>
|
|
1706
1706
|
`:``;if(m.innerHTML=`
|
|
1707
1707
|
<svg class="thinking-process-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
@@ -1714,7 +1714,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1714
1714
|
<svg class="thinking-process-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1715
1715
|
<polyline points="6 9 12 15 18 9"/>
|
|
1716
1716
|
</svg>
|
|
1717
|
-
`,f){let e=m.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),
|
|
1717
|
+
`,f){let e=m.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Je(f,e)}))}let _=document.createElement(`div`);_.className=`thinking-process-body`;let v=document.createElement(`div`);if(v.className=`thinking-process-content`,_.appendChild(v),l)for(;l.firstChild;)v.appendChild(l.firstChild);c.querySelectorAll(`.tool-call-item`).forEach(e=>v.appendChild(e)),v.querySelectorAll(`.preselect-card`).forEach(e=>e.remove());let y=(n||[]).filter(e=>e.nodeType===`preselect`);i.debug(`[finalizeStreamingMessage] executionLog length:`,(n||[]).length,`preselectEntries:`,y.length),y.forEach(e=>{i.debug(`[finalizeStreamingMessage] creating preselect card for entry:`,e);let t=FC(e);v.insertBefore(t,v.firstChild)});let b=v.querySelectorAll(`.thinking-content`),x=WC(t).trim();if(b.length>0){let e=b[b.length-1],t=e.textContent.trim();if(!s||s&&t===x){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(v.children.length>0&&v.textContent.trim()){p.appendChild(m),p.appendChild(_);let e=document.createElement(`div`);e.className=`final-answer`;let n=WC(t);n&&n.trim()&&(e.innerHTML=$e(n));let r=c.querySelector(`.thinking-indicator`);r&&r.remove(),l&&(l.innerHTML=``),c.appendChild(p),c.appendChild(e),IS(m)}else{let e=c.querySelector(`.thinking-indicator`);if(e&&e.remove(),l){let e=WC(t);e&&e.trim()&&(l.innerHTML=$e(e))}}}else if(l){let e=WC(t);if(l.querySelector(`.thinking-content`)){let t=US>0?Be(Date.now()-US):``,i=(n||[]).filter(e=>e.nodeType===`api_call`||e.nodeType===`tool_exec`),a=i.filter(e=>e.status===`success`).length,o=i.filter(e=>e.status===`failed`).length,u=i.length,d=We(n),f=document.createElement(`div`);f.className=`thinking-process collapsed`;let p=document.createElement(`div`);p.className=`thinking-process-header`;let m=u>0?`
|
|
1718
1718
|
<span class="thinking-process-stat">
|
|
1719
1719
|
<span class="stat-icon node-icon">◉</span>
|
|
1720
1720
|
<span class="stat-label">${r(`chatStream.totalNodes`)}</span>
|
|
@@ -1733,10 +1733,10 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1733
1733
|
</span>
|
|
1734
1734
|
`:``,h=d?`
|
|
1735
1735
|
${u>0?`<span class="thinking-process-divider">|</span>`:``}
|
|
1736
|
-
<span class="thinking-process-stat token-stat" title="${r(`chatStream.tokenUsageTitle`,{total:
|
|
1736
|
+
<span class="thinking-process-stat token-stat" title="${r(`chatStream.tokenUsageTitle`,{total:F(d.totalTokens),prompt:F(d.promptTokens),completion:F(d.completionTokens)})}">
|
|
1737
1737
|
<span class="stat-icon token-icon">⬤</span>
|
|
1738
1738
|
<span class="stat-label">${r(`chatStream.tokenLabel`)}</span>
|
|
1739
|
-
<span class="stat-value">${
|
|
1739
|
+
<span class="stat-value">${F(d.totalTokens)}</span>
|
|
1740
1740
|
</span>
|
|
1741
1741
|
`:``;if(p.innerHTML=`
|
|
1742
1742
|
<svg class="thinking-process-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
@@ -1749,7 +1749,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1749
1749
|
<svg class="thinking-process-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1750
1750
|
<polyline points="6 9 12 15 18 9"/>
|
|
1751
1751
|
</svg>
|
|
1752
|
-
`,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),qe(d,e)}))}let g=document.createElement(`div`);g.className=`thinking-process-body`;let _=document.createElement(`div`);for(_.className=`thinking-process-content`,g.appendChild(_);l.firstChild;)_.appendChild(l.firstChild);let v=_.querySelectorAll(`.thinking-content`),y=e.trim();if(v.length>0){let e=v[v.length-1],t=e.textContent.trim();if(!s||s&&t===y){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(_.children.length>0&&_.textContent.trim()){f.appendChild(p),f.appendChild(g);let t=document.createElement(`div`);t.className=`final-answer`,e&&e.trim()&&(t.innerHTML=$e(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),IS(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=$e(e))}}else e&&e.trim()&&(l.innerHTML=$e(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?dt(t):JSON.stringify(t),e.dataset.textContent_=dt(WC(t)),e.dataset.executionLog=JSON.stringify(n);let f=document.createElement(`div`);f.className=`message-footer`;let p=document.createElement(`button`);p.className=`copy-btn`,p.title=r(`chatStream.copyMarkdown`),p.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>`+r(`chatStream.copy`)+`</span>`].join(``),p.addEventListener(`click`,t=>{t.stopPropagation(),Wx(e,p,t)}),f.appendChild(p);let m=document.createElement(`button`);m.className=`quote-btn`,m.title=r(`chatStream.quoteTitle`),m.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>`+r(`chatStream.quote`)+`</span>`].join(``),m.addEventListener(`click`,t=>{t.stopPropagation(),Qx(e)}),f.appendChild(m),f.appendChild(wx());let h=document.createElement(`div`);h.className=`export-menu-container`;let g=document.createElement(`button`);g.className=`export-trigger-btn`,g.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>`+r(`chatStream.export`)+`</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let _=document.createElement(`div`);_.className=`export-dropdown`,_.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>`+r(`chatStream.exportWord`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>`+r(`chatStream.exportPdf`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>`+r(`chatStream.exportImage`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>`+r(`chatStream.exportMarkdown`)+`</span>`,`</button>`].join(``);let v=_.querySelector(`.export-docx-item`);v.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToDocx:n}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DIK7kXq9.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,0]));n(e,v,_)});let y=_.querySelector(`.export-md-item`);y.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToMarkdown:n}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DIK7kXq9.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,0]));n(e,y,_)});let b=_.querySelector(`.export-pdf-item`);b.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToPdf:n}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DIK7kXq9.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,0]));n(e,b,_)});let x=_.querySelector(`.export-image-item`);x.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToImage:n}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DIK7kXq9.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,0]));n(e,x,_)}),g.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.toggle(`show`)});let S=null;h.addEventListener(`mouseenter`,()=>{S=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.add(`show`)},300)}),h.addEventListener(`mouseleave`,()=>{S&&=(clearTimeout(S),null),setTimeout(()=>{!h.matches(`:hover`)&&!_.matches(`:hover`)&&_.classList.remove(`show`)},100)}),h.appendChild(g),h.appendChild(_),f.appendChild(h);let w=document.createElement(`div`);w.className=`footer-right-actions`,w.style.marginLeft=`auto`,w.style.display=`flex`,w.style.alignItems=`center`,w.style.gap=`8px`;let T=Pe(n);if(T){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:I(T.totalTokens),prompt:I(T.promptTokens),completion:I(T.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${I(T.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),qe(T,e)}),w.appendChild(e)}let E=Hy(t),D=Gy(n,t);if(E.length&&(e.dataset.declaredArtifacts=JSON.stringify(E)),lb(D),D.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:D.length}),e.innerHTML=`
|
|
1752
|
+
`,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Je(d,e)}))}let g=document.createElement(`div`);g.className=`thinking-process-body`;let _=document.createElement(`div`);for(_.className=`thinking-process-content`,g.appendChild(_);l.firstChild;)_.appendChild(l.firstChild);let v=_.querySelectorAll(`.thinking-content`),y=e.trim();if(v.length>0){let e=v[v.length-1],t=e.textContent.trim();if(!s||s&&t===y){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(_.children.length>0&&_.textContent.trim()){f.appendChild(p),f.appendChild(g);let t=document.createElement(`div`);t.className=`final-answer`,e&&e.trim()&&(t.innerHTML=$e(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),IS(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=$e(e))}}else e&&e.trim()&&(l.innerHTML=$e(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?ut(t):JSON.stringify(t),e.dataset.textContent_=ut(WC(t)),e.dataset.executionLog=JSON.stringify(n);let f=document.createElement(`div`);f.className=`message-footer`;let p=document.createElement(`button`);p.className=`copy-btn`,p.title=r(`chatStream.copyMarkdown`),p.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>`+r(`chatStream.copy`)+`</span>`].join(``),p.addEventListener(`click`,t=>{t.stopPropagation(),Wx(e,p,t)}),f.appendChild(p);let m=document.createElement(`button`);m.className=`quote-btn`,m.title=r(`chatStream.quoteTitle`),m.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>`+r(`chatStream.quote`)+`</span>`].join(``),m.addEventListener(`click`,t=>{t.stopPropagation(),Qx(e)}),f.appendChild(m),f.appendChild(wx());let h=document.createElement(`div`);h.className=`export-menu-container`;let g=document.createElement(`button`);g.className=`export-trigger-btn`,g.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>`+r(`chatStream.export`)+`</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let _=document.createElement(`div`);_.className=`export-dropdown`,_.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>`+r(`chatStream.exportWord`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>`+r(`chatStream.exportPdf`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>`+r(`chatStream.exportImage`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>`+r(`chatStream.exportMarkdown`)+`</span>`,`</button>`].join(``);let v=_.querySelector(`.export-docx-item`);v.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToDocx:n}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,v,_)});let y=_.querySelector(`.export-md-item`);y.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToMarkdown:n}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,y,_)});let b=_.querySelector(`.export-pdf-item`);b.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToPdf:n}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,b,_)});let x=_.querySelector(`.export-image-item`);x.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToImage:n}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,x,_)}),g.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.toggle(`show`)});let S=null;h.addEventListener(`mouseenter`,()=>{S=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.add(`show`)},300)}),h.addEventListener(`mouseleave`,()=>{S&&=(clearTimeout(S),null),setTimeout(()=>{!h.matches(`:hover`)&&!_.matches(`:hover`)&&_.classList.remove(`show`)},100)}),h.appendChild(g),h.appendChild(_),f.appendChild(h);let w=document.createElement(`div`);w.className=`footer-right-actions`,w.style.marginLeft=`auto`,w.style.display=`flex`,w.style.alignItems=`center`,w.style.gap=`8px`;let T=We(n);if(T){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:F(T.totalTokens),prompt:F(T.promptTokens),completion:F(T.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${F(T.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Je(T,e)}),w.appendChild(e)}let E=Hy(t),D=Gy(n,t);if(E.length&&(e.dataset.declaredArtifacts=JSON.stringify(E)),lb(D),D.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:D.length}),e.innerHTML=`
|
|
1753
1753
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1754
1754
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1755
1755
|
<polyline points="14 2 14 8 20 8"/>
|
|
@@ -1771,11 +1771,11 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1771
1771
|
<polyline points="3 6 5 6 21 6"></polyline>
|
|
1772
1772
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
|
1773
1773
|
</svg>
|
|
1774
|
-
`,te.addEventListener(`click`,t=>{t.stopPropagation(),Uw(e)}),w.appendChild(te),f.appendChild(w),e.querySelector(`.message-content`).appendChild(f),Nw(),Fw(),
|
|
1774
|
+
`,te.addEventListener(`click`,t=>{t.stopPropagation(),Uw(e)}),w.appendChild(te),f.appendChild(w),e.querySelector(`.message-content`).appendChild(f),Nw(),Fw(),rt(),ct(e),requestAnimationFrame(()=>{if(kS(),!TS){let t=document.getElementById(`chatContainer`);t&&e.offsetHeight>t.clientHeight*.6&&e.scrollIntoView({behavior:`smooth`,block:`start`})}OS()})}function LC(e){if(!e||e.disabled)return!1;try{document.dispatchEvent(new CustomEvent(`task-stop-requested`,{detail:{sessionId:C.activeSessionId}}))}catch{}e.disabled=!0,e.style.opacity=`0.4`,e.style.cursor=`not-allowed`;let t=document.querySelector(`.loading-message .stop-task-btn`);if(t){t.disabled=!0,t.style.opacity=`0.6`,t.style.cursor=`not-allowed`;let e=document.querySelector(`.loading-message .loading-text`);e&&(e.textContent=r(`chatStream.stopping`))}return chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:null,sessionId:C.activeSessionId}),C.pendingCancelApi&&C.pendingCancelApi({message:r(`chatStream.taskStopped`),executionLog:C.currentExecutionStatus?.executionLog||[]}),!0}function RC(e){if(!e)return;e.querySelectorAll(`.thinking-indicator`).forEach(e=>e.classList.add(`hidden`));let t=e.querySelector(`.stream-status`);t&&(t.textContent=``),e.querySelectorAll(`.tool-call-executing`).forEach(e=>{e.textContent=r(`chatStream.cancelled`),e.classList.add(`tool-call-cancelled`)}),e.querySelectorAll(`.subtask-status-label`).forEach(e=>{let t=e.querySelector(`.subtask-spinner`);t&&t.remove(),e.textContent.includes(r(`chatStream.executing`))&&(e.textContent=r(`chatStream.cancelled`))}),e.querySelectorAll(`.subtask-progress-active`).forEach(e=>e.classList.remove(`subtask-progress-active`)),e.querySelectorAll(`.subtask-node-spinner`).forEach(e=>e.replaceWith(`○`)),e.querySelectorAll(`.subtask-spinner, .thinking-spinner, .loading-dots`).forEach(e=>e.remove()),e.classList.remove(`streaming`),e.classList.add(`stream-cancelled`),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>e.style.display=`none`),e.querySelectorAll(`.tool-call-terminate-btn`).forEach(e=>e.style.display=`none`)}var zC=t({_checkForAbandonedCheckpoint:()=>aS,addContextBubble:()=>Ew,addLoadingMessage:()=>Iw,addMessage:()=>Aw,applyNodeFilter:()=>fw,bindExecutionLogDelegate:()=>Nw,bindReflectionBadgeDelegate:()=>Fw,bindSubtaskProgressClicks:()=>_w,buildKnowledgeContextText:()=>aw,buildUserContent:()=>Hp,callApi:()=>Gw,cancelStreamingTask:()=>LC,classifySubtaskNodeStats:()=>cw,classifySubtaskOutcome:()=>sw,clearChatHistory:()=>tw,clearSelectedContext:()=>qC,deleteMessage:()=>Uw,directSend:()=>Tw,editAndResendMessage:()=>Kw,extractSubtaskPlan:()=>hw,extractTextContent:()=>WC,fillSidePanelInput:()=>ww,hideModal:()=>rw,insertSubtaskRowInOrder:()=>vw,isSubtaskReplaySkipped:()=>uw,loadChatHistory:()=>ZC,mapApiErrorToUserMessage:()=>yw,openImagePreview:()=>Mp,rebindAllMessages:()=>Bw,refreshSelectionIndicatorFromState:()=>KC,removeLoadingMessage:()=>Lw,renderImagePreviewsFromChat:()=>Vp,renderKnowledgeContextBubbles:()=>ow,renderMessageMermaid:()=>ct,renderPendingSubtaskRow:()=>gw,resolveRunningNodeLabel:()=>lw,restoreMessageFromHtml:()=>zw,restorePendingSessionsFromStorage:()=>UC,saveChatHistory:()=>$C,saveChatHistoryAsync:()=>ew,sendMessage:()=>Sw,setMessageTimestampVisible:()=>jw,setQuoteContext:()=>GC,showCommandTerminateDialog:()=>Vw,showModal:()=>nw,stripImagesFromContent:()=>Up,syncPendingSessionsToStorage:()=>HC,toggleNodeFilter:()=>dw,triggerSelectionSearch:()=>Cw}),BC=new Set([`STREAM_START`,`STREAM_CHUNK`,`STREAM_TOOL_CALL`,`STREAM_DONE`]);Zx(GC),n(`zh`,{chatMsg:{searchPrompt:`搜索一下`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,executionLogTitle:`执行日志`,revisedTag:`已修订`,roundsTag:` ({count}轮)`,revisedSuffix:`(已修订)`,scoreBadgeTitle:`AI 质量评估: {score}/10{rounds}{revised}
|
|
1775
1775
|
点击查看评估详情`,reflectionFailedTitle:`反思评估失败(点击查看执行日志)`,reflectionFailedBadge:`⚠️ 反思失败`,prototypeLocalOpened:`已在本地浏览器打开,点击可在面板内查看`,prototypeView:`查看 UI 原型`,bookmarkMessage:`收藏消息`,unbookmarkMessage:`取消收藏`,forkSession:`从此处分叉会话(仅复制到此条消息)`,deleteMessageTitle:`删除消息`,resumeTaskTitle:`从上次中断处继续执行任务`,resumeTaskTitleBudget:`执行预算已用完(部分完成):点击后可在新的预算下接着未完成的部分继续`,resumeTaskBtn:`继续执行`,clickToEnlarge:`点击查看大图`,fileExtracting:` 提取中...`,fileFailed:` 失败`,fileExtractFailed:`提取失败`,copyMessageTitle:`复制消息内容`,editAndResend:`编辑后重新发送`,thinking:`思考中...`,stopTask:`停止任务`,viewExecutionLog:`查看执行日志`,preparing:`准备中...`,emptyModelReply:`模型未返回任何内容。若你发送了图片,请确认所选模型支持视觉识别(图片识别需选择支持多模态视觉的模型),或更换模型后重试。`,stopping:`停止中...`,copyCode:`复制代码`,aborting:`正在终止...`,terminateCommandTitle:`终止命令执行`,terminateCommandPrompt:`请选择终止方式:`,terminateWaitTitle:`终止等待`,terminateWaitDesc:`仅停止等待命令输出,后台进程继续运行。<br/>适用于挂起型服务(如 npm run dev)。`,terminateCommandBtnTitle:`终止命令`,terminateCommandBtnDesc:`直接终止后台命令进程,释放资源。`,confirmDeleteMessage:`确认删除消息`,deleteMessageWarning:`删除后消息将从对话历史中移除,且无法恢复。`,confirmDelete:`确认删除`,quotedContextLabel:`💬 已引用: {text}`,selectedContextLabel:`📌 已选中: {text}`,subtaskDone:`完成`,subtaskFailed:`失败`,subtaskPartial:`部分完成`,subtaskFailReason:`中断原因:{error}`,subtaskExecuting:`执行中...`,subtaskPending:`待执行`,subtaskDescLabel:`任务描述:`,subtaskResultLabel:`产出摘要:`,subtaskAllDone:`✓ 全部完成`,subtaskReplaySkipped:`已跳过重放`,subtaskReplaySkippedHint:`中断前已成功完成,本轮未重复执行,写操作不会二次生效`,subtaskFilterEmpty:`当前过滤下无匹配节点`,subtaskFilterHint:`点击按此状态过滤节点,再点取消`,subtaskStatOtherHint:`已取消 / 未完成节点(用户拒绝确认、任务终止时仍在执行等),点击过滤`,subtaskPartialFail:`✗ {success}/{total} 完成,{fail} 个节点失败`,unknownNode:`未知`,stopGeneration:`停止生成`,toolResultTitle:`执行结果`,reflectionInProgress:`质量评估中...`,cannotGetMessageContent:`无法获取消息内容`,editFailed:`编辑失败: {message}`,errTaskStopped:`任务已被用户停止`,errTaskReplaced:`任务已被新请求替代`,errSwRestarted:`后台服务异常重启,API 调用已中断`,errTimeout:`请求超时({seconds}秒)`,cancelBtn:`取消`}}),n(`en`,{chatMsg:{searchPrompt:`Search`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,executionLogTitle:`Execution Log`,revisedTag:`Revised`,roundsTag:` ({count} rounds)`,revisedSuffix:` (Revised)`,scoreBadgeTitle:`AI Quality Assessment: {score}/10{rounds}{revised}
|
|
1776
1776
|
Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection Failed`,prototypeLocalOpened:`Opened in local browser, click to view in panel`,prototypeView:`View UI Prototype`,bookmarkMessage:`Bookmark message`,unbookmarkMessage:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessageTitle:`Delete message`,resumeTaskTitle:`Resume task from last interruption`,resumeTaskTitleBudget:`Execution budget exhausted (partially complete): click to continue the unfinished parts with a fresh budget`,resumeTaskBtn:`Resume`,clickToEnlarge:`Click to view full size`,fileExtracting:` extracting...`,fileFailed:` failed`,fileExtractFailed:`Extraction failed`,copyMessageTitle:`Copy message content`,editAndResend:`Edit and resend`,thinking:`Thinking...`,stopTask:`Stop task`,viewExecutionLog:`View execution log`,preparing:`Preparing...`,emptyModelReply:`The model returned no content. If you sent an image, make sure the selected model supports vision (image recognition requires a multimodal vision model), or switch model and retry.`,stopping:`Stopping...`,copyCode:`Copy code`,aborting:`Aborting...`,terminateCommandTitle:`Terminate Command Execution`,terminateCommandPrompt:`Please select a termination method:`,terminateWaitTitle:`Stop Waiting`,terminateWaitDesc:`Only stop waiting for command output; the background process continues running.<br/>Suitable for hanging services (e.g. npm run dev).`,terminateCommandBtnTitle:`Terminate Command`,terminateCommandBtnDesc:`Directly terminate the background command process and release resources.`,confirmDeleteMessage:`Confirm Delete Message`,deleteMessageWarning:`After deletion, the message will be removed from the conversation history and cannot be recovered.`,confirmDelete:`Confirm Delete`,quotedContextLabel:`💬 Quoted: {text}`,selectedContextLabel:`📌 Selected: {text}`,subtaskDone:`Done`,subtaskFailed:`Failed`,subtaskPartial:`Partial`,subtaskFailReason:`Interrupted: {error}`,subtaskExecuting:`Executing...`,subtaskPending:`Pending`,subtaskDescLabel:`Description: `,subtaskResultLabel:`Output summary: `,subtaskAllDone:`✓ All done`,subtaskReplaySkipped:`replay skipped`,subtaskReplaySkippedHint:`Already completed before the interruption; not re-run this round, so side effects do not apply twice`,subtaskFilterEmpty:`No nodes match this filter`,subtaskFilterHint:`Click to filter nodes by this status, click again to clear`,subtaskStatOtherHint:`Cancelled / unfinished nodes (denied confirmations, still running when the task ended). Click to filter`,subtaskPartialFail:`✗ {success}/{total} done, {fail} nodes failed`,unknownNode:`Unknown`,stopGeneration:`Stop generation`,toolResultTitle:`Execution Result`,reflectionInProgress:`Assessing quality...`,cannotGetMessageContent:`Cannot get message content`,editFailed:`Edit failed: {message}`,errTaskStopped:`Task stopped by user`,errTaskReplaced:`Task replaced by new request`,errSwRestarted:`Background service restarted unexpectedly, API call interrupted`,errTimeout:`Request timeout ({seconds}s)`,cancelBtn:`Cancel`}});var VC=`pendingCallApiSessions`;function HC(){chrome.storage.session.set({[VC]:[...C.pendingCallApiSessionIds]}).catch(()=>{})}async function UC(){try{let e=await chrome.storage.session.get([VC]);e[VC]&&Array.isArray(e[VC])&&(C.pendingCallApiSessionIds=new Set(e[VC]))}catch{}}function WC(e){if(Array.isArray(e))return e.filter(e=>e.type===`text`).map(e=>e.text).join(``);if(typeof e==`string`&&e.startsWith(`[`))try{let t=JSON.parse(e);if(Array.isArray(t))return t.filter(e=>e.type===`text`).map(e=>e.text).join(``)}catch{}return e}function GC(e){let t=WC(e);C.quotedContextText=t;let n=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(n&&i&&a){let e;e=t.length>100?t.substring(0,100)+`...`:t.length>50?t.substring(0,50)+`...`:t,i.textContent=r(`chat.quotedPrefix`,{text:e}),n.classList.add(`show`)}}function KC(){let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`selectionText`);if(!e||!t)return;let n=(C.quotedContextText||``).trim(),i=(C.selectedContextText||``).trim(),a=n||i;if(!a){e.classList.remove(`show`);return}let o;o=a.length>100?a.substring(0,100)+`...`:a.length>50?a.substring(0,50)+`...`:a,t.textContent=r(n?`chatMsg.quotedContextLabel`:`chatMsg.selectedContextLabel`,{text:o}),e.classList.add(`show`)}function qC(){i.debug(`[SidePanel] clear selectedcontenttext `),C.selectedContextText=``,C.quotedContextText=``;let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`userInput`);if(e&&(e.classList.remove(`show`),i.debug(`[SidePanel] hiddenselected contentprompt`)),typeof window.hideFloatingMenu==`function`&&window.hideFloatingMenu(),t&&t.value.startsWith(`[选中内容]`)){let e=t.value.split(`
|
|
1777
1777
|
`),n=e.findIndex(e=>e.startsWith(`[用户问题]`));n===-1?t.value=``:t.value=e.slice(n+1).join(`
|
|
1778
|
-
`).trim()}}var JC,YC=new Promise(e=>{JC=e});function XC(){C.activeSessionId&&document.dispatchEvent(new CustomEvent(`session-hydrated`,{detail:{sessionId:C.activeSessionId,workdir:C.sessionWorkdir||null}}))}async function ZC(){try{await QC()}finally{JC(),document.dispatchEvent(new CustomEvent(`chat-history-rendered`,{detail:{sessionId:C.activeSessionId||null}}))}}async function QC(){let e=await ti();if(e.activeSessionId&&e.list.length>0){C.activeSessionId=e.activeSessionId,C.sessions=e.list;let t=e.list.find(t=>t.id===e.activeSessionId);if(t){if(C.messageHistory=t.messageHistory||[],C.activeCompaction=t.contextCompaction||null,ri(t),XC(),C.currentModel=t.model||C.currentModel,C.useTools=t.useTools===void 0?C.useTools:t.useTools,C.temperature=t.temperature===void 0?C.temperature:t.temperature,C.topP=t.topP===void 0?C.topP:t.topP,C.activeAgentId=t.agentId||null,C.activeAgentId&&C.activeAgentId!=="default"){try{let{getAgent:e}=await A(async()=>{let{getAgent:e}=await import(`./agent-store-CE4-QMOA.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3])),t=await e(C.activeAgentId);t&&(C.activeAgentMcpExcludedServerIds=t.mcpExcludedServerIds??null,t.model&&(C.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(C.temperature=t.temperature,C.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`)))}catch{}C.activeAgentMcpExcludedServerIds=null}else{C.activeAgentMcpExcludedServerIds=null;try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(C.currentModel=e.modelName),e.temperature!==void 0&&(C.temperature=e.temperature),e.topP!==void 0&&(C.topP=e.topP)}catch{}document.dispatchEvent(new CustomEvent(`agent-model-changed`))}let e=`agentMcpClosedServers_${C.activeAgentId||`default`}`;C.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}let n=document.getElementById(`chatContainer`);n&&n.querySelectorAll(`.message, .user-context-bubble`).forEach(e=>e.remove()),C.messageHistory.forEach(e=>{let t=e.wasRevised;if(!t&&e.executionLog)try{t=(typeof e.executionLog==`string`?JSON.parse(e.executionLog):e.executionLog).some(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.action?.decision===`revised`)}catch{}if(e.role===`user`&&e.contextBubbles&&Array.isArray(e.contextBubbles)&&e.contextBubbles.forEach(e=>{let t=``;switch(e.type){case`skill`:t=r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``});break;case`mcp`:t=r(`contextBubble.bubbleMcp`,{name:e.serverName});break;case`page`:t=r(`contextBubble.bubblePage`,{title:e.title,url:e.url});break;case`file`:t=`${e.name} (${pm(e.size||0)})`;break;case`knowledge`:{let t=Array.isArray(e.refs)?e.refs:[];t.length>0&&ow(t,e.failed===!0);break}}t&&e.type!==`file`&&Ew(e.type,t,!1)}),e.htmlContent)zw(e.htmlContent,e.messageId,e.resumable);else{let n=(e.contextBubbles||[]).filter(e=>e.type===`file`).map(e=>({name:e.name,size:e.size||0,type:e.fileType||``}));Aw(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,t,null,e.messageId,n,e.resumable,e.timestamp??null)}}),Nw(),Fw(),
|
|
1778
|
+
`).trim()}}var JC,YC=new Promise(e=>{JC=e});function XC(){C.activeSessionId&&document.dispatchEvent(new CustomEvent(`session-hydrated`,{detail:{sessionId:C.activeSessionId,workdir:C.sessionWorkdir||null}}))}async function ZC(){try{await QC()}finally{JC(),document.dispatchEvent(new CustomEvent(`chat-history-rendered`,{detail:{sessionId:C.activeSessionId||null}}))}}async function QC(){let e=await ti();if(e.activeSessionId&&e.list.length>0){C.activeSessionId=e.activeSessionId,C.sessions=e.list;let t=e.list.find(t=>t.id===e.activeSessionId);if(t){if(C.messageHistory=t.messageHistory||[],C.activeCompaction=t.contextCompaction||null,ri(t),XC(),C.currentModel=t.model||C.currentModel,C.useTools=t.useTools===void 0?C.useTools:t.useTools,C.temperature=t.temperature===void 0?C.temperature:t.temperature,C.topP=t.topP===void 0?C.topP:t.topP,C.activeAgentId=t.agentId||null,C.activeAgentId&&C.activeAgentId!=="default"){try{let{getAgent:e}=await A(async()=>{let{getAgent:e}=await import(`./agent-store-CE4-QMOA.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3])),t=await e(C.activeAgentId);t&&(C.activeAgentMcpExcludedServerIds=t.mcpExcludedServerIds??null,t.model&&(C.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(C.temperature=t.temperature,C.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`)))}catch{}C.activeAgentMcpExcludedServerIds=null}else{C.activeAgentMcpExcludedServerIds=null;try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(C.currentModel=e.modelName),e.temperature!==void 0&&(C.temperature=e.temperature),e.topP!==void 0&&(C.topP=e.topP)}catch{}document.dispatchEvent(new CustomEvent(`agent-model-changed`))}let e=`agentMcpClosedServers_${C.activeAgentId||`default`}`;C.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}let n=document.getElementById(`chatContainer`);n&&n.querySelectorAll(`.message, .user-context-bubble`).forEach(e=>e.remove()),C.messageHistory.forEach(e=>{let t=e.wasRevised;if(!t&&e.executionLog)try{t=(typeof e.executionLog==`string`?JSON.parse(e.executionLog):e.executionLog).some(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.action?.decision===`revised`)}catch{}if(e.role===`user`&&e.contextBubbles&&Array.isArray(e.contextBubbles)&&e.contextBubbles.forEach(e=>{let t=``;switch(e.type){case`skill`:t=r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``});break;case`mcp`:t=r(`contextBubble.bubbleMcp`,{name:e.serverName});break;case`page`:t=r(`contextBubble.bubblePage`,{title:e.title,url:e.url});break;case`file`:t=`${e.name} (${pm(e.size||0)})`;break;case`knowledge`:{let t=Array.isArray(e.refs)?e.refs:[];t.length>0&&ow(t,e.failed===!0);break}}t&&e.type!==`file`&&Ew(e.type,t,!1)}),e.htmlContent)zw(e.htmlContent,e.messageId,e.resumable);else{let n=(e.contextBubbles||[]).filter(e=>e.type===`file`).map(e=>({name:e.name,size:e.size||0,type:e.fileType||``}));Aw(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,t,null,e.messageId,n,e.resumable,e.timestamp??null)}}),Nw(),Fw(),ot();let i=document.querySelector(`.welcome-message`);i&&C.messageHistory.length>0&&i.remove(),Ye(),rt(),aD(),e.activeSessionId===C.activeSessionId?yo(e):yo(),await aS();let a=`scrollPosition_`+(C.activeSessionId||`default`);chrome.storage.local.get([a],e=>{e[a]!==void 0&&setTimeout(()=>{let t=document.getElementById(`chatContainer`);t.scrollTop=e[a]},100)})}else{await ai();let e=await ti();e.activeSessionId&&(C.activeSessionId=e.activeSessionId,C.sessions=e.list,ri(e.list.find(t=>t.id===e.activeSessionId)),XC()),yo(e)}}function $C(){try{ni().catch(e=>{i.error(`[SidePanel] save currentsession failed:`,e)})}catch(e){i.error(`[SidePanel] save conversationhistory exception:`,e)}}async function ew(){try{await ni()}catch(e){i.error(`[SidePanel] save conversationhistory exception:`,e)}}function tw(){C.messageHistory&&C.messageHistory.length>0&&ui().then(()=>{C.messageHistory=[],C.activeCompaction=null;let e=document.getElementById(`chatContainer`);if(e){e.innerHTML=``;let t=document.createElement(`div`);t.className=`welcome-message`,t.innerHTML=`
|
|
1779
1779
|
<div class="icon-wrapper">
|
|
1780
1780
|
<div class="icon">💬</div>
|
|
1781
1781
|
</div>
|
|
@@ -1784,14 +1784,14 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1784
1784
|
`,e.appendChild(t)}chrome.storage.local.remove(`scrollPosition_`+(C.activeSessionId||`default`)),yo()})}function nw(){document.getElementById(`confirmModal`).classList.add(`show`)}function rw(){document.getElementById(`confirmModal`).classList.remove(`show`)}var iw=1500;async function aw(e,t){if(!t||t.length===0)return null;let{ragEnabled:n}=await chrome.storage.local.get(`ragEnabled`);if(n!==!0)return i.debug(`[SidePanel] RAG global switch off, skip knowledge context`),null;let a=await new Promise(n=>{try{chrome.runtime.sendMessage({type:`RAG_SEARCH`,params:{query:e,collectionIds:t.map(e=>e.id).filter(Boolean),topK:5}},e=>{if(chrome.runtime.lastError){n(null);return}n(e&&e.success?e:null)})}catch{n(null)}}),o=!a,s=a&&a.results||[],c=new Map(t.filter(e=>e.id).map(e=>[e.id,e.name])),l=new Map;s.forEach(e=>{let t=e.collectionId||``,n=l.get(t);n||(n={id:t,name:c.get(t)||t||r(`contextBubble.labelKnowledge`),hitCount:0,items:[]},l.set(t,n)),n.items.push(e),n.hitCount++});let u=Array.from(l.values()),d=s.length,f=e=>e.map(e=>{let t=String(e.content||``).trim();return{score:typeof e.score==`number`?e.score:Number(e.score)||0,content:t.slice(0,iw),truncated:t.length>iw,fullLength:t.length}}),p=t.map(e=>({id:e.id,name:e.name,hitCount:e.id&&l.get(e.id)?.hitCount||0,hits:e.id?f(l.get(e.id)?.items||[]):[]}));u.forEach(e=>{p.some(t=>t.id&&t.id===e.id)||p.push({id:e.id,name:e.name,hitCount:e.hitCount,hits:f(e.items)})});let m=[`[知识库检索结果](引用: ${t.map(e=>e.name).join(`、`)})`];return o?m.push(`知识库检索失败:检索服务暂时不可用(这不代表知识库中没有相关内容)。`):d===0?m.push(`未找到与问题相关的内容。`):u.forEach(e=>{m.push(``),m.push(`【${e.name}】`),e.items.forEach(e=>{let t=typeof e.score==`number`?e.score.toFixed(3):String(e.score??``);m.push(`· 相关度 ${t}`),m.push(String(e.content||``).trim().slice(0,iw)),m.push(``)})}),m.push(`[/知识库检索结果]`),{text:m.join(`
|
|
1785
1785
|
`)+`
|
|
1786
1786
|
|
|
1787
|
-
`,refs:p,failed:o}}function ow(e,t=!1){if(!Array.isArray(e)||e.length===0)return;let n=e.reduce((e,t)=>e+(t.hitCount||0),0);if(t){Ew(`knowledge`,r(`contextBubble.bubbleKnowledgeFailed`,{name:e.map(e=>e.name).join(`、`)}),!1);return}if(n===0){Ew(`knowledge`,r(`contextBubble.bubbleKnowledgeMiss`,{name:e.map(e=>e.name).join(`、`)}),!1);return}e.forEach(e=>{(e.hitCount||0)>0?Ew(`knowledge`,r(`contextBubble.bubbleKnowledge`,{name:e.name,count:e.hitCount}),!1,Array.isArray(e.hits)?e.hits:null):Ew(`knowledge`,r(`contextBubble.bubbleKnowledgeMiss`,{name:e.name}),!1)})}function sw(e,t,n,r=.8){return e===`failed`?!n||n<=0?`failed`:t/n>=r?`partial`:`failed`:e}function cw(e){let t=Array.isArray(e)?e:[],n=0,r=0;for(let e of t)e&&e.status===`success`?n++:e&&e.status===`failed`&&r++;return{total:t.length,success:n,failed:r,other:t.length-n-r}}function lw(e){let t=e&&e.nodeName?e.nodeName:r(`chatMsg.subtaskExecuting`);return
|
|
1787
|
+
`,refs:p,failed:o}}function ow(e,t=!1){if(!Array.isArray(e)||e.length===0)return;let n=e.reduce((e,t)=>e+(t.hitCount||0),0);if(t){Ew(`knowledge`,r(`contextBubble.bubbleKnowledgeFailed`,{name:e.map(e=>e.name).join(`、`)}),!1);return}if(n===0){Ew(`knowledge`,r(`contextBubble.bubbleKnowledgeMiss`,{name:e.map(e=>e.name).join(`、`)}),!1);return}e.forEach(e=>{(e.hitCount||0)>0?Ew(`knowledge`,r(`contextBubble.bubbleKnowledge`,{name:e.name,count:e.hitCount}),!1,Array.isArray(e.hits)?e.hits:null):Ew(`knowledge`,r(`contextBubble.bubbleKnowledgeMiss`,{name:e.name}),!1)})}function sw(e,t,n,r=.8){return e===`failed`?!n||n<=0?`failed`:t/n>=r?`partial`:`failed`:e}function cw(e){let t=Array.isArray(e)?e:[],n=0,r=0;for(let e of t)e&&e.status===`success`?n++:e&&e.status===`failed`&&r++;return{total:t.length,success:n,failed:r,other:t.length-n-r}}function lw(e){let t=e&&e.nodeName?e.nodeName:r(`chatMsg.subtaskExecuting`);return I(String(t))}function uw(e,t){return(Array.isArray(e)?e:[]).some(e=>!!e&&e.nodeType===`subtask`&&e.subtaskIndex===t&&e.skippedReplay===!0)}function dw(e,t){return t!==`success`&&t!==`failed`&&t!==`other`?e||null:e===t?null:t}function fw(e,t){let n=Array.isArray(e)?e:[];return t!==`success`&&t!==`failed`&&t!==`other`?n:t===`other`?n.filter(e=>!e||e.status!==`success`&&e.status!==`failed`):n.filter(e=>e&&e.status===t)}var pw=`<svg class="subtask-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="17" rx="2"/><line x1="8" y1="2" x2="8" y2="4"/><line x1="16" y1="2" x2="16" y2="4"/><line x1="3" y1="10" x2="21" y2="10"/></svg>`,mw=`<svg class="subtask-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>`;function hw(e){let t=Array.isArray(e)?e:[],n=null;for(let e of t)!e||e.nodeType!==`subtask_plan`||!Array.isArray(e.items)||(!n||new Date(e.timestamp||0)>=new Date(n.timestamp||0))&&(n=e);if(!n)return null;let r=n.items,i=r.filter(e=>e&&typeof e.index==`number`);return{total:n.subtaskTotal||r.length,items:i,timestamp:n.timestamp}}function gw(e,t){let n=e.description?String(e.description).replace(/\s+/g,` `).trim():``,i=n?`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${I(n)}</div>`:``;return`
|
|
1788
1788
|
<div class="subtask-header">
|
|
1789
|
-
${mw}${pw}${`<span class="subtask-badge">${e.index+1}/${t}</span>`}<span class="subtask-name" title="${
|
|
1789
|
+
${mw}${pw}${`<span class="subtask-badge">${e.index+1}/${t}</span>`}<span class="subtask-name" title="${Me(n)}">${I(e.name||``)}</span><span class="subtask-status-pending">${r(`chatMsg.subtaskPending`)}</span>
|
|
1790
1790
|
</div>
|
|
1791
1791
|
<div class="subtask-detail-body">${i}</div>
|
|
1792
|
-
`}function _w(e){!e||e._clickDelegated||(e._clickDelegated=!0,e.addEventListener(`click`,t=>{let n=t.target.closest(`[data-node-filter]`);if(n){t.stopPropagation(),e._nodeFilter=dw(e._nodeFilter||null,n.dataset.nodeFilter),e._nodeFilter&&e.classList.add(`subtask-expanded`),e._renderNodes?.();return}t.target.closest(`.subtask-header`)&&e.classList.toggle(`subtask-expanded`)}))}function vw(e,t){let n=Number(t.dataset.subtaskIndex),r=Array.from(e.querySelectorAll(`.subtask-progress[data-subtask-index]`)).find(e=>Number(e.dataset.subtaskIndex)>n);r?e.insertBefore(t,r):e.appendChild(t)}function yw(e){let t=e||r(`chatResume.unknownError`),n=t.toLowerCase();return n.includes(`network`)||n.includes(`failed to fetch`)||n.includes(`load failed`)?r(`chat.networkError`):n.includes(`timeout`)||t.includes(`超时`)?r(`chat.timeoutError`,{message:t}):r(`chat.requestFailed`,{message:t})}var bw=Object.freeze({quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,attachedFiles:[],attachedImages:[]});function xw(){return{quotedContextText:C.quotedContextText||``,selectedContextText:C.selectedContextText||``,selectedSkills:(C.selectedSkills||[]).slice(),selectedMcpServices:(C.selectedMcpServices||[]).slice(),knowledgeRefs:(C.knowledgeRefs||[]).slice(),selectedPage:C.selectedPage||null,attachedFiles:(C.attachedFiles||[]).slice(),attachedImages:(C.attachedImages||[]).slice()}}async function Sw(e={}){await YC;let t=document.getElementById(`userInput`),n=document.getElementById(`chatContainer`),a=e.sessionId||C.activeSessionId,o=a===C.activeSessionId,l=o?null:e.sessionState||{},u=o?C.messageHistory:l.messageHistory||[],d=e.context||(o?xw():bw),f=!e.context,h=o?C.currentModel:l.model||C.currentModel,g=o||l.useTools===void 0?C.useTools:l.useTools,_=o?C.enabledTools:l.enabledTools||C.enabledTools,v=o?C.activeCompaction:l.contextCompaction||null,y=String(e.text==null?t?.value||``:e.text).trim(),x=y||od(d);if(!x)return{ok:!1,reason:`empty`};if(o&&f&&dd())return
|
|
1792
|
+
`}function _w(e){!e||e._clickDelegated||(e._clickDelegated=!0,e.addEventListener(`click`,t=>{let n=t.target.closest(`[data-node-filter]`);if(n){t.stopPropagation(),e._nodeFilter=dw(e._nodeFilter||null,n.dataset.nodeFilter),e._nodeFilter&&e.classList.add(`subtask-expanded`),e._renderNodes?.();return}t.target.closest(`.subtask-header`)&&e.classList.toggle(`subtask-expanded`)}))}function vw(e,t){let n=Number(t.dataset.subtaskIndex),r=Array.from(e.querySelectorAll(`.subtask-progress[data-subtask-index]`)).find(e=>Number(e.dataset.subtaskIndex)>n);r?e.insertBefore(t,r):e.appendChild(t)}function yw(e){let t=e||r(`chatResume.unknownError`),n=t.toLowerCase();return n.includes(`network`)||n.includes(`failed to fetch`)||n.includes(`load failed`)?r(`chat.networkError`):n.includes(`timeout`)||t.includes(`超时`)?r(`chat.timeoutError`,{message:t}):r(`chat.requestFailed`,{message:t})}var bw=Object.freeze({quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,attachedFiles:[],attachedImages:[]});function xw(){return{quotedContextText:C.quotedContextText||``,selectedContextText:C.selectedContextText||``,selectedSkills:(C.selectedSkills||[]).slice(),selectedMcpServices:(C.selectedMcpServices||[]).slice(),knowledgeRefs:(C.knowledgeRefs||[]).slice(),selectedPage:C.selectedPage||null,attachedFiles:(C.attachedFiles||[]).slice(),attachedImages:(C.attachedImages||[]).slice()}}async function Sw(e={}){await YC;let t=document.getElementById(`userInput`),n=document.getElementById(`chatContainer`),a=e.sessionId||C.activeSessionId,o=a===C.activeSessionId,l=o?null:e.sessionState||{},u=o?C.messageHistory:l.messageHistory||[],d=e.context||(o?xw():bw),f=!e.context,h=o?C.currentModel:l.model||C.currentModel,g=o||l.useTools===void 0?C.useTools:l.useTools,_=o?C.enabledTools:l.enabledTools||C.enabledTools,v=o?C.activeCompaction:l.contextCompaction||null,y=String(e.text==null?t?.value||``:e.text).trim(),x=y||od(d);if(!x)return{ok:!1,reason:`empty`};if(o&&f&&dd())return P(r(`queue.filesStillExtracting`),`warning`,4e3),{ok:!1,reason:`files_extracting`};if(e.fromQueue||Uu(),C.generatingSessionIds.has(a))return{ok:!1,reason:`generating`};try{let e=await chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`,sessionId:a});if(e?.running===!0||Array.isArray(e?.activeSessionIds)&&e.activeSessionIds.includes(a)||e?.activeCallIds&&e.activeCallIds[a])return{ok:!1,reason:`generating`}}catch{}if(nS(a),chrome.runtime.sendMessage({type:`DELETE_CHECKPOINT`,sessionId:a}),o&&await Xc({state:C,getRatio:()=>WE().usage?.ratio??0,compact:$E}),o){let e=n?.querySelector(`.welcome-message`);e&&e.remove()}let S=x,w=d.selectedContextText&&d.selectedContextText.trim(),T=d.quotedContextText&&d.quotedContextText.trim(),D=[];if(T){let e=d.quotedContextText.trim(),{compressed:t,wasCompressed:n}=m(e);S=`[引用内容${n?`摘要`:``}]\n${t}\n\n[用户问题]\n${x}`,o&&Ew(`quoted`,e,!1),D.push({type:`quoted`,text:e}),o&&f&&C.quotedContextText===d.quotedContextText&&(C.quotedContextText=``)}else if(w){let e=d.selectedContextText.trim(),{compressed:t,wasCompressed:n}=m(e);S=`[选中内容${n?`摘要`:``}]\n${t}\n\n[用户问题]\n${x}`,o&&Ew(`selected`,e,!1),D.push({type:`selected`,text:e}),o&&f&&C.selectedContextText===d.selectedContextText&&(C.selectedContextText=``)}let O=await FT(d.selectedSkills);if(O){S=O+S;for(let e of d.selectedSkills||[])o&&Ew(`skill`,r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``}),!1),D.push({type:`skill`,name:e.name,description:e.description||``});if(o){let e=new Set(d.selectedSkills||[]),t=C.selectedSkills.filter(t=>!e.has(t));t.length!==C.selectedSkills.length&&(C.selectedSkills=t,C.selectedSkillIndex=-1,kT(),AT())}}let k=null,A=HT(d.selectedMcpServices);if(A){let e=(d.selectedMcpServices||[]).map(e=>e.serverId).filter(Boolean);k=e.length>0?e:null,S=A+S;for(let e of d.selectedMcpServices||[])o&&Ew(`mcp`,r(`contextBubble.bubbleMcp`,{name:e.serverName}),!1),D.push({type:`mcp`,serverName:e.serverName,serverId:e.serverId||``});if(o){let e=new Set(d.selectedMcpServices||[]),t=C.selectedMcpServices.filter(t=>!e.has(t));t.length!==C.selectedMcpServices.length&&(C.selectedMcpServices=t,C.selectedMcpServiceIndex=-1,UT(),WT())}}if((d.knowledgeRefs||[]).length>0){let e=d.knowledgeRefs.slice();o&&(C.isGenerating=!0);let t=o?Ew(`knowledge`,r(`contextBubble.bubbleKnowledgeSearching`),!0):null,n=null;try{n=await aw(y||r(`sidePanel.defaultKnowledgeQuery`),e)}catch(e){i.warn(`[SidePanel] knowledge search failed:`,e)}if(t&&t.parentNode&&t.remove(),n&&(S=n.text+S,o&&ow(n.refs,n.failed===!0),D.push({type:`knowledge`,refs:n.refs,failed:n.failed||void 0})),o){let t=new Set(e),n=C.knowledgeRefs.filter(e=>!t.has(e));n.length!==C.knowledgeRefs.length&&(C.knowledgeRefs=n,Rb(),Hb())}}if(d.selectedPage){let e=d.selectedPage;S=`[网页上下文]\n标题: ${e.title}\nURL: ${e.url}\ntabId: ${e.id}\n`+S,o&&Ew(`page`,r(`contextBubble.bubblePage`,{title:e.title,url:e.url}),!1),D.push({type:`page`,title:e.title,url:e.url}),o&&C.selectedPage===d.selectedPage&&nx()}let M=!1,N=(d.attachedFiles||[]).slice();if(N.length>0){let e=jm(N);e&&(S+=e),N.forEach(e=>{e.status===`done`&&D.push({type:`file`,name:e.name,size:e.size,fileType:e.type})})}let ee=(d.attachedImages||[]).slice(),te=null;if(N.length>0||ee.length>0)try{te=await j(a,N,ee)}catch(e){i.warn(`[Chat] save doc image snapshot failed:`,e.message)}let ne=Te(te?.chatStart,te?.chatCount);ne&&(S+=ne);let re=`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8),ie=new Date().toISOString(),ae={role:`user`,content:Hp(S,d.attachedImages),messageId:re,timestamp:ie,contextBubbles:D};o?(Aw(`user`,Hp(x,d.attachedImages),!0,[],null,!1,S,re,N,!1,ie),C.messageHistory.push(ae),$C(),y&&cn(y),C.inputHistoryIndex=-1):u.push(ae),M=!0,o&&!e.fromQueue&&(t.value=``,t.style.height=`auto`),o&&(w||T)&&(!C.quotedContextText&&!C.selectedContextText?qC():KC()),C.generatingSessionIds.add(a),document.dispatchEvent(new CustomEvent(`generating-state-changed`));let oe=o?Iw():null,se=C.enableImageInput&&(d.attachedImages||[]).length>0&&C.imageModelName||h;if(o&&(d.attachedImages||[]).length>0){let e=new Set(d.attachedImages),t=C.attachedImages.filter(t=>!e.has(t));t.length!==C.attachedImages.length&&(C.attachedImages=t,Vp())}if(o&&N.length>0){let e=new Set(N),t=C.attachedFiles.filter(t=>!e.has(t));if(t.length!==C.attachedFiles.length){for(let t of C.attachedFiles)e.has(t)&&t.dataUrl&&URL.revokeObjectURL(t.dataUrl);C.attachedFiles=t,Am()}}let ce=e=>{if(!o){u.push(e);return}if(C.activeSessionId!==a){_i(a,e);return}C.messageHistory.push(e)};try{await nt();let e=await FE(o?C.activeAgentId:l.agentId||null),t=IE(e),n=e?.skillIds??null;o&&(C.activeAgentToolIds=t,C.activeAgentSkillIds=n,C.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null);let f={agentId:o?C.activeAgentId:l.agentId||null,agentToolIds:t,agentSkillIds:n,agentMcpExcludedServerIds:e?e.mcpExcludedServerIds??null:null};i.debug(`[SidePanel] sendmessagedebuginfo:`),i.debug(` - agent:`,e?e.name:`default assistant`),i.debug(` - agentToolIds:`,t),i.debug(` - isolateChat:`,C.isolateChat),i.debug(` - chatConfig:`,C.chatConfig),i.debug(` - messageHistory.length:`,u.length);let m=[{role:`system`,content:await Ge(e,{sessionId:a})}];if(C.isolateChat){let e=s(m[0]?.content||``),t=p(se,0,C.customModelMap)-e-4096-2e3;Math.floor(t*.7);let n=u[u.length-1],r=nn(u.slice(0,-1),{isolateChat:!0,maxMemoryMessages:C.chatConfig.maxMemoryMessages,compaction:v,currentMessage:n});an(m,r,v,i),r.historySummaryText&&(m[0]={...m[0],content:m[0].content+`
|
|
1793
1793
|
|
|
1794
|
-
`+r.historySummaryText}),i.debug(`[SidePanel] history selection: keep ${r.keptHistory.length}/${u.length-1}, trimmed ${r.trimmedCount}, compactionApplied: ${r.compactionApplied}`),m=[...m,...r.messages];for(let e=0;e<m.length-1;e++)m[e]={...m[e],content:Up(m[e].content)}}else{let e=Hp(S,d.attachedImages);m.push({role:`user`,content:e})}let h=await
|
|
1794
|
+
`+r.historySummaryText}),i.debug(`[SidePanel] history selection: keep ${r.keptHistory.length}/${u.length-1}, trimmed ${r.trimmedCount}, compactionApplied: ${r.compactionApplied}`),m=[...m,...r.messages];for(let e=0;e<m.length-1;e++)m[e]={...m[e],content:Up(m[e].content)}}else{let e=Hp(S,d.attachedImages);m.push({role:`user`,content:e})}let h=await Ne(o?null:{temperature:l.temperature,topP:l.topP});if(o&&(h._loadingId=oe),o)try{let e=await xf({sessionId:a,text:x,attachments:Sf(d)});e&&(h.goal=e)}catch(e){i.warn(`[SidePanel] prepare goal for send failed:`,e?.message)}let y=E(m),w=p(se,0,C.customModelMap),T=c(y,w);if(i.debug(`[SidePanel] send context: ${y} tokens (message: ${m.length} ), pressure: ${T.level}(${Math.round(T.ratio*100)}%)`),T.level===`critical`){i.warn(`[SidePanel] context pressure too high,maindynamictrimming...`);let e=s(m[0]?.content||``),t=await Ww(k),n=(_.length+t)*200,r=w-e-n-4096-2e3,a=b(m,Math.max(r,2e3),{generateSummary:!1});m=a.messages,i.warn(`[SidePanel] proactively trimmed: ${y} → ${E(m)} tokens (${a.trimmedCount} )`)}let D,O,A,j=!1,M=!1,N=null,ee=!0,te=null,ne=!1;try{let e=await Gw(m,se,g,h,{forcedMcpServerIds:k,sessionId:a,agent:f});D=e.content,O=e.executionLog||[],A=e.reflectionScore,j=e.wasRevised||!1,M=e.wasStreamed||!1,N=e.streamingHtml||null,ee=e.streamingConnected===void 0?!0:e.streamingConnected,te=e.streamingMsgId||null,ne=e.budgetEnded===!0}catch(e){if(!o||C.activeSessionId!==a){let t=!!e.checkpoint||e.swRestarted||e.message===r(`chatMsg.errTaskStopped`);return ce({role:`assistant`,content:e.message===r(`chatMsg.errTaskStopped`)?r(`chatResume.taskCancelled`):e.swRestarted?r(`chat.taskInterruptedSwRestart`):yw(e.message),executionLog:e.executionLog||[],resumable:t}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:a}})),oe&&Lw(oe),C.substituteLoadingIds.delete(a),{ok:!1,delivered:!0,reason:`inactive`}}if(e.message===r(`chatMsg.errTaskStopped`)){oe&&Lw(oe),C.substituteLoadingIds.delete(a);let{messageId:t}=Aw(`assistant`,r(`chatResume.taskCancelled`),!1,e.executionLog||[],null,!1,null,null,[],!0);return C.messageHistory.push({role:`assistant`,content:r(`chatResume.taskCancelled`),executionLog:e.executionLog||[],messageId:t,resumable:!0}),$C(),{ok:!1,delivered:!0,reason:`cancelled`}}if(e.swRestarted){oe&&Lw(oe),C.substituteLoadingIds.delete(a);let t=!!e.checkpoint,{messageId:n}=Aw(`assistant`,r(`chat.taskInterruptedSwRestart`),!1,e.executionLog||[],null,!1,null,null,[],t);return C.messageHistory.push({role:`assistant`,content:r(`chat.taskInterruptedSwRestart`),executionLog:e.executionLog||[],messageId:n,resumable:t}),$C(),Ol(a,r(`chat.taskInterruptedSwRestart`),x),{ok:!1,delivered:!0,reason:`sw_restarted`}}oe&&Lw(oe),C.substituteLoadingIds.delete(a),D=yw(e.message),O=e.executionLog||[];let{messageId:t}=Aw(`assistant`,D,!0,O,A,!1,null,null,[],!0);return C.messageHistory.push({role:`assistant`,content:D,executionLog:O,reflectionScore:A,messageId:t,resumable:!0}),Ol(a,D,x),{ok:!1,delivered:!0,reason:`error`}}if(!o||C.activeSessionId!==a){let e={role:`assistant`,content:D,executionLog:O,reflectionScore:A,wasRevised:j,resumable:ne?`budget`:!1,messageId:te||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8)};return M&&N&&(e.htmlContent=N),ce(e),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:a}})),oe&&Lw(oe),C.substituteLoadingIds.delete(a),{ok:!0,delivered:!0}}let re=null;if(!M||!N)if(oe&&Lw(oe),C.substituteLoadingIds.has(a)&&(Lw(C.substituteLoadingIds.get(a)),C.substituteLoadingIds.delete(a)),M)C.substituteLoadingIds.has(a)&&(Lw(C.substituteLoadingIds.get(a)),C.substituteLoadingIds.delete(a)),re=te;else{let{element:e,messageId:t}=Aw(`assistant`,D,!0,O,A,j,null,null,[],ne?`budget`:!1);re=t,await ct(e),PS()}else re=te;ne&&iS(re?document.querySelector(`[data-message-id="${re}"]`):null,`budget`);let ie={role:`assistant`,content:D,executionLog:O,reflectionScore:A,wasRevised:j,resumable:ne?`budget`:!1,messageId:re};if(M&&N&&(ie.htmlContent=N,!ee&&!document.querySelector(`[data-message-id="${re}"]`))){zw(N,re,ne?`budget`:!1),Nw(),Fw();let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}return C.messageHistory.push(ie),Dl(a,x),{ok:!0,delivered:!0}}catch(e){return i.error(`[SidePanel] sendMessage exception:`,e?.message||e),{ok:!1,delivered:M,reason:e?.message||`exception`}}finally{o?$C():(await ii(a,{messageHistory:u,model:l.model,useTools:l.useTools,enabledTools:l.enabledTools,agentId:l.agentId,temperature:l.temperature,topP:l.topP,activeCompaction:l.contextCompaction,workdir:l.workdir,workdirAgentId:l.workdirAgentId,goalMode:l.goalMode}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:a}}))),jl(a),o&&t.focus()}}function Cw(e,t){let n=document.getElementById(`userInput`);if(!t||C.isGenerating){i.debug(`[SidePanel] triggerSelectionSearch skip:`,{hasText:!!t,isGenerating:C.isGenerating});return}C.selectedContextText=t,C.quotedContextText=``,n.value=r(`chatMsg.searchPrompt`),n.dispatchEvent(new Event(`input`)),Sw()}function ww(e){let t=document.getElementById(`userInput`);!t||!e||(t.value=e,t.dispatchEvent(new Event(`input`)),t.focus())}async function Tw(e,t=``){await YC;let n=document.getElementById(`userInput`);if(!(!n||!e)){if(t&&(C.selectedContextText=t,C.quotedContextText=``),C.isGenerating){n.value=e,n.dispatchEvent(new Event(`input`)),await hd();return}n.value=e,n.dispatchEvent(new Event(`input`)),n.focus(),Sw()}}function Ew(e,t,n=!0,i=null){let a=document.getElementById(`chatContainer`),o=document.createElement(`div`);o.className=`user-context-bubble`,o.dataset.role=`context`;let s=e===`quoted`?`💬`:e===`skill`?`🧩`:e===`mcp`?`🔌`:e===`page`?`🌐`:e===`file`?`📎`:e===`knowledge`?`📚`:`📌`,c=r(e===`quoted`?`contextBubble.labelQuoted`:e===`skill`?`contextBubble.labelSkill`:e===`mcp`?`contextBubble.labelMcp`:e===`page`?`contextBubble.labelPage`:e===`file`?`contextBubble.labelFile`:e===`knowledge`?`contextBubble.labelKnowledge`:`contextBubble.labelSelection`),l=I(t);if(e===`knowledge`&&Array.isArray(i)&&i.length>0){let e=i.map(e=>{let t=typeof e.score==`number`?e.score.toFixed(3):``,n=t?`<span class="kb-bubble-hit-score">${t}</span>`:``,i=e.truncated?`<span class="kb-bubble-hit-truncated" title="${r(`contextBubble.kbHitTruncatedTitle`)}">${r(`contextBubble.kbHitTruncated`,{total:e.fullLength||0,kept:iw})}</span>`:``;return`<div class="kb-bubble-hit"><div class="kb-bubble-hit-text" title="${r(`contextBubble.kbHitToggle`)}">${n}${I(e.content||``)}</div>${i}</div>`}).join(``),n=i.filter(e=>e.truncated).length,a=n>0?`<span class="kb-bubble-truncated-badge">${r(`contextBubble.kbHitTruncatedBadge`,{count:n})}</span>`:``;l=`<div class="kb-bubble-summary">${I(t)}${a}</div>${e}`}o.innerHTML=`
|
|
1795
1795
|
<div class="context-bubble-inner">
|
|
1796
1796
|
<div class="context-bubble-header" title="${r(`contextBubble.clickToExpand`)}">
|
|
1797
1797
|
<span class="context-icon">${s}</span>
|
|
@@ -1799,7 +1799,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1799
1799
|
</div>
|
|
1800
1800
|
<div class="context-bubble-content">${l}</div>
|
|
1801
1801
|
</div>
|
|
1802
|
-
`;let u=o.querySelector(`.context-bubble-header`),d=o.querySelector(`.context-bubble-content`);return u.addEventListener(`click`,e=>{e.stopPropagation(),d.classList.toggle(`expanded`)}),e===`knowledge`&&o.querySelectorAll(`.kb-bubble-hit-text`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),e.classList.toggle(`expanded`)})}),a.appendChild(o),n&&(a.scrollTop=a.scrollHeight),o}function Dw(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n[\s\S]*?(?:请根据上述技能说明[\s\S]*?处理以下问题[::]|Please use the relevant tools[\s\S]*?handle the following problem[.:])\s*\n/,``).replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n(?:请|Please)[^\n]*(?:处理以下问题|handle the following problem)[^。\n]*。?\s*\n/,``);while(t!==n);return t}function Ow(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选MCP服务|Selected MCP service):\s*[^\]]+\]\n(?:请使用「[^」]+」MCP服务来处理以下问题:|Please use the "[^"]+" MCP service to handle the following problem:)\s*\n/,``);while(t!==n);return t}var kw=e=>!!e&&e.dataset.resumable===`budget`;function Aw(e,t,n=!0,a=[],o=null,s=!1,c=null,l=null,u=[],d=!1,f=void 0){let p=document.getElementById(`chatContainer`),m=document.createElement(`div`);m.className=`message ${e}`;let h=f===void 0?new Date().toISOString():f||null;h&&(m.dataset.timestamp=h);let g=l||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);m.dataset.messageId=g;let _=Array.isArray(t)?t.filter(e=>e.type===`text`).map(e=>e.text).join(``):t,v=e===`user`?fe(_):_,y=Array.isArray(t)&&t.some(e=>e.type===`image_url`);m.dataset.rawContent=Array.isArray(t)?JSON.stringify(t):dt(t),m.dataset.textContent_=dt(e===`user`?fe(c||v):c||v);let b=v;if(m.dataset.executionLog=JSON.stringify(a),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=$e(t);let e=document.createElement(`div`);e.className=`message-footer`;let n=document.createElement(`button`);n.className=`copy-btn`,n.title=r(`chatStream.copyMarkdown`),n.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>${r(`common.copy`)}</span>`].join(``),n.addEventListener(`click`,e=>{e.stopPropagation(),Wx(m,n,e)}),e.appendChild(n);let c=document.createElement(`button`);c.className=`quote-btn`,c.title=r(`chat.quoteTitle`),c.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>${r(`chat.quote`)}</span>`].join(``),c.addEventListener(`click`,e=>{e.stopPropagation(),Qx(m)}),e.appendChild(c),e.appendChild(wx());let l=document.createElement(`div`);l.className=`export-menu-container`;let u=document.createElement(`button`);u.className=`export-trigger-btn`,u.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>${r(`chat.export`)}</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let f=document.createElement(`div`);f.className=`export-dropdown`,f.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>${r(`chatMsg.exportWord`)}</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>${r(`chatMsg.exportPdf`)}</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>${r(`chatMsg.exportImage`)}</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>${r(`chatMsg.exportMarkdown`)}</span>`,`</button>`].join(``);let p=f.querySelector(`.export-docx-item`);p.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToDocx:t}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DIK7kXq9.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,0]));t(m,p,f)});let h=f.querySelector(`.export-md-item`);h.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToMarkdown:t}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DIK7kXq9.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,0]));t(m,h,f)});let _=f.querySelector(`.export-pdf-item`);_.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToPdf:t}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DIK7kXq9.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,0]));t(m,_,f)});let v=f.querySelector(`.export-image-item`);v.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToImage:t}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DIK7kXq9.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,0]));t(m,v,f)}),u.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.toggle(`show`)});let y=null;l.addEventListener(`mouseenter`,()=>{y=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.add(`show`)},300)}),l.addEventListener(`mouseleave`,()=>{y&&=(clearTimeout(y),null),setTimeout(()=>{!l.matches(`:hover`)&&!f.matches(`:hover`)&&f.classList.remove(`show`)},100)}),l.appendChild(u),l.appendChild(f),e.appendChild(l);let b=document.createElement(`div`);b.className=`footer-right-actions`,b.style.marginLeft=`auto`,b.style.display=`flex`,b.style.alignItems=`center`,b.style.gap=`8px`;let x=Pe(a);if(x){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:I(x.totalTokens),prompt:I(x.promptTokens),completion:I(x.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${I(x.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),qe(x,e)}),b.appendChild(e)}let S=a&&a.length>0,w=o!=null,T=a?a.filter(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.status===`success`).length:0;Nw(),Fw(),st();let E=a?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),D=Hy(t),O=Gy(a,t);if(D.length&&(m.dataset.declaredArtifacts=JSON.stringify(D)),lb(O),console.log(`[addMessage] executionLog entries:`,a?.length,`| agent_file entries:`,a?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length,`| artifacts:`,O.length),O.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:O.length}),e.innerHTML=`
|
|
1802
|
+
`;let u=o.querySelector(`.context-bubble-header`),d=o.querySelector(`.context-bubble-content`);return u.addEventListener(`click`,e=>{e.stopPropagation(),d.classList.toggle(`expanded`)}),e===`knowledge`&&o.querySelectorAll(`.kb-bubble-hit-text`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),e.classList.toggle(`expanded`)})}),a.appendChild(o),n&&(a.scrollTop=a.scrollHeight),o}function Dw(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n[\s\S]*?(?:请根据上述技能说明[\s\S]*?处理以下问题[::]|Please use the relevant tools[\s\S]*?handle the following problem[.:])\s*\n/,``).replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n(?:请|Please)[^\n]*(?:处理以下问题|handle the following problem)[^。\n]*。?\s*\n/,``);while(t!==n);return t}function Ow(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选MCP服务|Selected MCP service):\s*[^\]]+\]\n(?:请使用「[^」]+」MCP服务来处理以下问题:|Please use the "[^"]+" MCP service to handle the following problem:)\s*\n/,``);while(t!==n);return t}var kw=e=>!!e&&e.dataset.resumable===`budget`;function Aw(e,t,n=!0,a=[],o=null,s=!1,c=null,l=null,u=[],d=!1,f=void 0){let p=document.getElementById(`chatContainer`),m=document.createElement(`div`);m.className=`message ${e}`;let h=f===void 0?new Date().toISOString():f||null;h&&(m.dataset.timestamp=h);let g=l||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);m.dataset.messageId=g;let _=Array.isArray(t)?t.filter(e=>e.type===`text`).map(e=>e.text).join(``):t,v=e===`user`?fe(_):_,y=Array.isArray(t)&&t.some(e=>e.type===`image_url`);m.dataset.rawContent=Array.isArray(t)?JSON.stringify(t):ut(t),m.dataset.textContent_=ut(e===`user`?fe(c||v):c||v);let b=v;if(m.dataset.executionLog=JSON.stringify(a),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=$e(t);let e=document.createElement(`div`);e.className=`message-footer`;let n=document.createElement(`button`);n.className=`copy-btn`,n.title=r(`chatStream.copyMarkdown`),n.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>${r(`common.copy`)}</span>`].join(``),n.addEventListener(`click`,e=>{e.stopPropagation(),Wx(m,n,e)}),e.appendChild(n);let c=document.createElement(`button`);c.className=`quote-btn`,c.title=r(`chat.quoteTitle`),c.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>${r(`chat.quote`)}</span>`].join(``),c.addEventListener(`click`,e=>{e.stopPropagation(),Qx(m)}),e.appendChild(c),e.appendChild(wx());let l=document.createElement(`div`);l.className=`export-menu-container`;let u=document.createElement(`button`);u.className=`export-trigger-btn`,u.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>${r(`chat.export`)}</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let f=document.createElement(`div`);f.className=`export-dropdown`,f.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>${r(`chatMsg.exportWord`)}</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>${r(`chatMsg.exportPdf`)}</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>${r(`chatMsg.exportImage`)}</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>${r(`chatMsg.exportMarkdown`)}</span>`,`</button>`].join(``);let p=f.querySelector(`.export-docx-item`);p.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToDocx:t}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,p,f)});let h=f.querySelector(`.export-md-item`);h.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToMarkdown:t}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,h,f)});let _=f.querySelector(`.export-pdf-item`);_.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToPdf:t}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,_,f)});let v=f.querySelector(`.export-image-item`);v.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToImage:t}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,v,f)}),u.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.toggle(`show`)});let y=null;l.addEventListener(`mouseenter`,()=>{y=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.add(`show`)},300)}),l.addEventListener(`mouseleave`,()=>{y&&=(clearTimeout(y),null),setTimeout(()=>{!l.matches(`:hover`)&&!f.matches(`:hover`)&&f.classList.remove(`show`)},100)}),l.appendChild(u),l.appendChild(f),e.appendChild(l);let b=document.createElement(`div`);b.className=`footer-right-actions`,b.style.marginLeft=`auto`,b.style.display=`flex`,b.style.alignItems=`center`,b.style.gap=`8px`;let x=We(a);if(x){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:F(x.totalTokens),prompt:F(x.promptTokens),completion:F(x.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${F(x.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Je(x,e)}),b.appendChild(e)}let S=a&&a.length>0,w=o!=null,T=a?a.filter(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.status===`success`).length:0;Nw(),Fw(),ot();let E=a?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),D=Hy(t),O=Gy(a,t);if(D.length&&(m.dataset.declaredArtifacts=JSON.stringify(D)),lb(O),console.log(`[addMessage] executionLog entries:`,a?.length,`| agent_file entries:`,a?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length,`| artifacts:`,O.length),O.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:O.length}),e.innerHTML=`
|
|
1803
1803
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1804
1804
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1805
1805
|
<polyline points="14 2 14 8 20 8"/>
|
|
@@ -1826,7 +1826,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1826
1826
|
<polyline points="3 6 5 6 21 6"></polyline>
|
|
1827
1827
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
|
1828
1828
|
</svg>
|
|
1829
|
-
`,l.addEventListener(`click`,e=>{e.stopPropagation(),Uw(m)}),o.appendChild(l),m.appendChild(o),h){m.classList.add(`has-time`);let e=document.createElement(`time`);e.className=`message-time`,e.dateTime=h,e.textContent=
|
|
1829
|
+
`,l.addEventListener(`click`,e=>{e.stopPropagation(),Uw(m)}),o.appendChild(l),m.appendChild(o),h){m.classList.add(`has-time`);let e=document.createElement(`time`);e.className=`message-time`,e.dateTime=h,e.textContent=Ie(h),e.title=ze(h),m.appendChild(e)}}if(p.appendChild(m),m._pendingContext){let{type:e,contextText:t}=m._pendingContext,n=Ew(e,t,!1);p.insertBefore(n,m),delete m._pendingContext}return n&&AS(p,{smooth:!0}),e===`assistant`&&rt(),{element:m,messageId:g,timestamp:h}}function jw(e){let t=document.getElementById(`chatContainer`);t&&t.classList.toggle(`timestamps-hidden`,e===!1)}var Mw=!1;function Nw(){if(Mw)return;let e=document.getElementById(`chatContainer`);e&&(e.addEventListener(`click`,e=>{let t=e.target.closest(`.execution-log-btn`);if(!t)return;let n=t.closest(`.message`);if(!n)return;e.preventDefault(),e.stopPropagation();let r=n.dataset.executionLog;if(r)try{let e=JSON.parse(r);i.debug(`[chat-manager] exec log buttonclick(delegate), entries:`,e.length),eS(e)}catch(e){i.error(`[chat-manager] parse executionLog failed:`,e)}}),Mw=!0)}var Pw=!1;function Fw(){if(Pw)return;let e=document.getElementById(`chatContainer`);e&&(e.addEventListener(`click`,e=>{let t=e.target.closest(`.reflection-score-btn`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.dataset.reflectionData;if(n)try{$x(JSON.parse(n),t)}catch(e){i.error(`[chat-manager] parse reflectionData failed:`,e)}}),Pw=!0)}function Iw(){let e=document.getElementById(`chatContainer`),t=`loading-`+Date.now(),n=document.createElement(`div`);n.className=`loading-message`,n.id=t,n.innerHTML=`
|
|
1830
1830
|
<div class="loading-content">
|
|
1831
1831
|
<div class="loading-dots">
|
|
1832
1832
|
<span></span>
|
|
@@ -1862,11 +1862,11 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1862
1862
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1863
1863
|
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
|
|
1864
1864
|
</svg>
|
|
1865
|
-
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{_w(e)}),s.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),Vw(C.activeSessionId)})}),s.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:C.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})});let l=s.querySelector(`.message-footer`);if(l){let e=l.querySelector(`.copy-btn`);e&&e.addEventListener(`click`,t=>{t.stopPropagation(),Wx(s,e,t)});let t=l.querySelector(`.quote-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Qx(s)});let n=l.querySelector(`.export-trigger-btn`),r=l.querySelector(`.export-dropdown`);n&&r&&(n.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==r&&e.classList.remove(`show`)}),r.classList.toggle(`show`)}),r.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToDocx:n}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-
|
|
1865
|
+
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{_w(e)}),s.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),Vw(C.activeSessionId)})}),s.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:C.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})});let l=s.querySelector(`.message-footer`);if(l){let e=l.querySelector(`.copy-btn`);e&&e.addEventListener(`click`,t=>{t.stopPropagation(),Wx(s,e,t)});let t=l.querySelector(`.quote-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Qx(s)});let n=l.querySelector(`.export-trigger-btn`),r=l.querySelector(`.export-dropdown`);n&&r&&(n.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==r&&e.classList.remove(`show`)}),r.classList.toggle(`show`)}),r.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToDocx:n}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(s,t,r)}),r.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToMarkdown:n}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(s,t,r)}),r.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToPdf:n}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(s,t,r)}),r.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToImage:n}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(s,t,r)}));let a=l.querySelector(`.prototype-btn-small`);if(a){let e=(()=>{try{let e=s.dataset.executionLog;return e?JSON.parse(e):[]}catch{return[]}})().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);e&&a.addEventListener(`click`,()=>{let t=e.prototypeId;if(!t&&e.observation)try{t=(typeof e.observation==`string`?JSON.parse(e.observation):e.observation)?.prototypeId}catch{}t?Cc(t):i.error(`[SidePanel] not found prototypeId,entry keys:`,Object.keys(e),`observation:`,e.observation)})}let o=l.querySelector(`.bookmark-btn`);o&&(qm(o,C.activeSessionId,s.dataset.messageId),o.addEventListener(`click`,async e=>{e.stopPropagation();let t=C.activeSessionId,n=s.dataset.messageId;if(o.classList.contains(`bookmarked`)){await Fm(t,n),qm(o,t,n);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>zm);return{refreshBookmarkPanel:e}},void 0);e()}else{await Pm(t,n,s.dataset.textContent_||``,C.sessions.find(e=>e.id===t)?.title||``),qm(o,t,n);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>zm);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=l.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),Uw(s)});let u=l.querySelector(`.fork-btn`);u&&u.addEventListener(`click`,async e=>{e.stopPropagation();let t=s.dataset.messageId;t&&await Xs(C.activeSessionId,t)});let d=l.querySelector(`.resume-task-btn`);d&&d.addEventListener(`click`,async e=>{if(e.stopPropagation(),d.disabled)return;let t=await tS({budgetEnded:kw(s)});t!==null&&(d.disabled=!0,d.style.opacity=`0.6`,d.style.cursor=`not-allowed`,oS(C.activeSessionId,t).finally(()=>{d.disabled=!1,d.style.opacity=``,d.style.cursor=``}))}),Rw(s);let f=l.querySelector(`.token-usage-tag`);f&&!f._clickBound&&(f._clickBound=!0,f.style.cursor=`pointer`,f.addEventListener(`click`,e=>{e.stopPropagation();try{let e=s.dataset.executionLog,t=We(e?JSON.parse(e):[]);t&&Je(t,f)}catch{}}))}let u=s.querySelector(`.message-toolbar`);if(u){let e=u.querySelector(`.edit-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),Kw(s)});let t=u.querySelector(`.copy-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Ux(s,t)});let n=u.querySelector(`.delete-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),Uw(s)})}s.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{Mp(e.src,e)})}),a.appendChild(s),aD()}function Bw(e){e.querySelectorAll(`.tool-call-body > pre, .tool-result-content > pre, .agent-stream-output > pre`).forEach(e=>{if(e.parentElement.classList.contains(`code-block-container`))return;let t=document.createElement(`div`);t.className=`code-block-container`,t.style.position=`relative`,t.innerHTML=`<button class="code-copy-btn" title="${r(`chatMsg.copyCode`)}">
|
|
1866
1866
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1867
1867
|
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
|
|
1868
1868
|
</svg>
|
|
1869
|
-
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{IS(e)}),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=e.closest(`.tool-call-item`);n&&n.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`);if(!t)return;let n=t.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),e.querySelectorAll(`.subtask-progress`).forEach(e=>{_w(e)}),e.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),Vw(C.activeSessionId)})}),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:C.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})}),e.querySelectorAll(`.message-footer`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.copy-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),Wx(t,n,e)});let r=e.querySelector(`.quote-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Qx(t)});let i=e.querySelector(`.export-trigger-btn`),a=e.querySelector(`.export-dropdown`);i&&a&&(i.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==a&&e.classList.remove(`show`)}),a.classList.toggle(`show`)}),a.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToDocx:r}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-
|
|
1869
|
+
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{IS(e)}),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=e.closest(`.tool-call-item`);n&&n.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`);if(!t)return;let n=t.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),e.querySelectorAll(`.subtask-progress`).forEach(e=>{_w(e)}),e.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),Vw(C.activeSessionId)})}),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:C.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})}),e.querySelectorAll(`.message-footer`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.copy-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),Wx(t,n,e)});let r=e.querySelector(`.quote-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Qx(t)});let i=e.querySelector(`.export-trigger-btn`),a=e.querySelector(`.export-dropdown`);i&&a&&(i.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==a&&e.classList.remove(`show`)}),a.classList.toggle(`show`)}),a.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToDocx:r}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));r(t,n,a)}),a.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToMarkdown:r}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));r(t,n,a)}),a.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToPdf:r}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));r(t,n,a)}),a.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToImage:r}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DZntnUPd.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));r(t,n,a)}));let o=e.querySelector(`.prototype-btn-small`);if(o){let e=(()=>{try{let e=t.dataset.executionLog;return e?JSON.parse(e):[]}catch{return[]}})().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);e&&o.addEventListener(`click`,()=>{let t=e.prototypeId;if(!t&&e.observation)try{t=(typeof e.observation==`string`?JSON.parse(e.observation):e.observation)?.prototypeId}catch{}t&&Cc(t)})}let s=e.querySelector(`.bookmark-btn`);s&&(qm(s,C.activeSessionId,t.dataset.messageId),s.addEventListener(`click`,async e=>{e.stopPropagation();let n=C.activeSessionId,r=t.dataset.messageId;if(s.classList.contains(`bookmarked`)){await Fm(n,r),qm(s,n,r);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>zm);return{refreshBookmarkPanel:e}},void 0);e()}else{await Pm(n,r,t.dataset.textContent_||``,C.sessions.find(e=>e.id===n)?.title||``),qm(s,n,r);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>zm);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=e.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),Uw(t)});let l=e.querySelector(`.fork-btn`);l&&l.addEventListener(`click`,async e=>{e.stopPropagation();let n=t.dataset.messageId;n&&await Xs(C.activeSessionId,n)});let u=e.querySelector(`.resume-task-btn`);u&&u.addEventListener(`click`,async e=>{if(e.stopPropagation(),u.disabled)return;let n=await tS({budgetEnded:kw(t)});n!==null&&(u.disabled=!0,u.style.opacity=`0.6`,u.style.cursor=`not-allowed`,oS(C.activeSessionId,n).finally(()=>{u.disabled=!1,u.style.opacity=``,u.style.cursor=``}))}),Rw(t);let d=e.querySelector(`.token-usage-tag`);d&&!d._clickBound&&(d._clickBound=!0,d.style.cursor=`pointer`,d.addEventListener(`click`,e=>{e.stopPropagation();try{let e=t.dataset.executionLog,n=We(e?JSON.parse(e):[]);n&&Je(n,d)}catch{}}))}),e.querySelectorAll(`.message-toolbar`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.edit-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),Kw(t)});let r=e.querySelector(`.copy-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Ux(t,r)});let i=e.querySelector(`.delete-btn`);i&&i.addEventListener(`click`,e=>{e.stopPropagation(),Uw(t)})}),e.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{Mp(e.src,e)})}),e.querySelectorAll(`.mermaid-controls`).forEach(e=>e.remove()),Ze(),Nw(),Fw(),aD()}function Vw(e){return new Promise(t=>{let n=document.querySelector(`.command-terminate-overlay`);n&&n.remove();let i=document.createElement(`div`);i.className=`command-terminate-overlay`,i.innerHTML=`
|
|
1870
1870
|
<div class="command-terminate-modal">
|
|
1871
1871
|
<div class="command-terminate-header">
|
|
1872
1872
|
<div class="command-terminate-icon">⏹</div>
|
|
@@ -1918,8 +1918,8 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1918
1918
|
<h2>${r(`chat.welcomeTitle`)}</h2>
|
|
1919
1919
|
<p>${r(`chat.welcomeSubtitle`)}</p>
|
|
1920
1920
|
</div>
|
|
1921
|
-
`),await ew(),n&&C.activeSessionId&&y(C.activeSessionId,n).then(e=>{e||i.warn(`[SidePanel] IndexedDB messagecleanup failed, messageId:`,n)}).catch(e=>{i.error(`[SidePanel] IndexedDB messagecleanup exception:`,e)}),i.debug(`[SidePanel] deletedmessage: ${a}, messageId: ${n}`)}async function Ww(e=null){try{let{mcpTools:t}=await chrome.storage.local.get([`mcpTools`]),n=t||[],r=new Set(Array.isArray(C.mcpClosedServers)?C.mcpClosedServers:[]),i=new Set(Array.isArray(C.activeAgentMcpExcludedServerIds)?C.activeAgentMcpExcludedServerIds:[]),a=new Set(Array.isArray(e)?e:[]);return n.filter(e=>{let t=e.serverId||`unknown`;return a.has(t)?!0:!r.has(t)&&!i.has(t)}).length}catch{return 0}}async function Gw(e,t,n=!1,a={},o={}){let{resumeFromCheckpoint:s=!1,userGuidance:c=``,loadingId:l=null,forcedMcpServerIds:u=null,sessionId:d=null,agent:f=null}=o,p=f?f.agentId:C.activeAgentId,m=f?f.agentToolIds:C.activeAgentToolIds,h=f?f.agentSkillIds:C.activeAgentSkillIds,g=f?f.agentMcpExcludedServerIds:C.activeAgentMcpExcludedServerIds,_=await
|
|
1922
|
-
<span class="subtask-current-node"><span class="subtask-current-spinner"></span><span class="node-label">${e} ${t}</span>${n?` <span class="subtask-current-cmd" title="${
|
|
1921
|
+
`),await ew(),n&&C.activeSessionId&&y(C.activeSessionId,n).then(e=>{e||i.warn(`[SidePanel] IndexedDB messagecleanup failed, messageId:`,n)}).catch(e=>{i.error(`[SidePanel] IndexedDB messagecleanup exception:`,e)}),i.debug(`[SidePanel] deletedmessage: ${a}, messageId: ${n}`)}async function Ww(e=null){try{let{mcpTools:t}=await chrome.storage.local.get([`mcpTools`]),n=t||[],r=new Set(Array.isArray(C.mcpClosedServers)?C.mcpClosedServers:[]),i=new Set(Array.isArray(C.activeAgentMcpExcludedServerIds)?C.activeAgentMcpExcludedServerIds:[]),a=new Set(Array.isArray(e)?e:[]);return n.filter(e=>{let t=e.serverId||`unknown`;return a.has(t)?!0:!r.has(t)&&!i.has(t)}).length}catch{return 0}}async function Gw(e,t,n=!1,a={},o={}){let{resumeFromCheckpoint:s=!1,userGuidance:c=``,loadingId:l=null,forcedMcpServerIds:u=null,sessionId:d=null,agent:f=null}=o,p=f?f.agentId:C.activeAgentId,m=f?f.agentToolIds:C.activeAgentToolIds,h=f?f.agentSkillIds:C.activeAgentSkillIds,g=f?f.agentMcpExcludedServerIds:C.activeAgentMcpExcludedServerIds,_=await Re(),v=(_.toolTimeout||0)+3*(_.apiTimeout||0)+6e4,y=_.loopTimeout+v,b=await new Promise(e=>{chrome.storage.local.get(`reflectionConfig`,t=>{e(t.reflectionConfig||{enabled:!1})})}),x=d||C.activeSessionId,S=s?`resume_${Date.now()}_${Math.random().toString(36).substring(2,8)}`:`call_${Date.now()}_${Math.random().toString(36).substring(2,8)}`;if(i.debug(`[SidePanel] callApi: generating callId: ${S}${s?` (restoremode)`:``}`),s&&l&&(a={...a,_loadingId:l}),C.pendingCancelApiMap&&C.pendingCancelApiMap.has(x)){i.debug(`[SidePanel] callApi: detectedsession has ongoing API call with , first cancelold`);let e=C.pendingCancelApiMap.get(x);e&&e({message:r(`chatMsg.errTaskReplaced`),executionLog:[]})}C.pendingCallApiSessionIds&&C.pendingCallApiSessionIds.has(x)&&(C.pendingCallApiSessionIds.delete(x),HC());let w=GS(x),T=null,E=chrome.runtime.connect({name:`keepalive-`+x});i.debug(`[SidePanel] keepalive portconnected, sessionId:`,x),nl(x);try{let e=tl();E.postMessage({type:`KEEPALIVE_IDENTITY`,identity:e==null?null:{windowId:e}})}catch{}let D={restarted:!1,rejectFn:null,cleanup:null,checkpoint:null};E.onMessage.addListener(e=>{if(BC.has(e.type)){if(T&&(T(e),e.callId&&e.callId===S))try{E.postMessage({type:`STREAM_CHUNK_ACK`,sessionId:x,callId:e.callId,seq:e.seq})}catch{}return}if(e.type===`HOST_TAB_RESOLVED`&&e.sessionId===x){rl(x,e.hostTabId);return}e.type===`SW_RESTARTED`&&e.sessionId===x&&(i.warn(`[SidePanel] ⚠️ recei to SW_RESTARTED notification,background re started,API call lost`),D.restarted=!0,D.checkpoint=e.checkpoint||null,D.rejectFn&&D.cleanup&&(D.cleanup(),D.rejectFn({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:D.checkpoint,swRestarted:!0}))),e.type===`SHOW_CLARIFY_DIALOG`?za(e.data):e.type===`CLARIFY_TIMEOUT`?Ga(e):e.type===`CLARIFY_EXTENDED`?ka(e):e.type===`SHOW_CONFIRM_DIALOG`?co(e.data):e.type===`DISMISS_CONFIRM_DIALOG`&&fo(e.data)});let O={timeoutId:null,removeListener:()=>{}},k=()=>{try{E.disconnect()}catch{}T=null,O.timeoutId&&=(clearTimeout(O.timeoutId),null),O.removeListener(),C.pendingCancelApiMap.delete(x),C.pendingCallApiSessionIds.delete(x),KS(x),HC()};return new Promise((o,l)=>{if(D.cleanup=k,D.rejectFn=l,D.restarted){k(),l({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:D.checkpoint,swRestarted:!0});return}let d=[],f=Math.round(_.loopTimeout/1e3);w(null),XS(null),eC(0);let v=``,E=new Map,A=e=>{w()&&(xC(w(),v),RC(w())),k(),(!e.executionLog||e.executionLog.length===0||d.length>0)&&(e.executionLog=d),l(e)};C.pendingCancelApiMap.set(x,A),C.pendingCallApiSessionIds.add(x),HC(),i.debug(`[SidePanel] callApi: add pendingCallApiSessionIds, mySessionId =`,x,`, set:`,[...C.pendingCallApiSessionIds]),O.timeoutId=setTimeout(()=>{A({message:r(`chatMsg.errTimeout`,{seconds:f}),executionLog:d}),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:C.currentTabId,sessionId:x}).catch(e=>{i.debug(`[SidePanel] sendcancelrequest failed:`,e.message)})},y);let j=Date.now(),M=0,N=null,ee=()=>{N===null&&O.timeoutId!==null&&(N=Date.now(),clearTimeout(O.timeoutId),O.timeoutId=null,i.debug(`[SidePanel] before sidetimeoutpaused (waitinguser response:clarification/sensitive toolconfirm)`))},te=()=>{if(N!==null){let e=Date.now()-N;M+=e,N=null;let t=Date.now()-j,n=y+M-t;if(n<=0){A({message:r(`chatMsg.errTimeout`,{seconds:f}),executionLog:d});return}O.timeoutId=setTimeout(()=>{A({message:r(`chatMsg.errTimeout`,{seconds:f}),executionLog:d}),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:C.currentTabId,sessionId:x}).catch(e=>{i.debug(`[SidePanel] sendcancelrequest failed:`,e.message)})},n),i.debug(`[SidePanel] before sidetimeoutrestored,pause duration:`,Math.round(e/1e3),`s,remaining time:`,Math.round(n/1e3),`s`)}},ne=e=>{if(e.sessionId&&e.sessionId!==x||e.callId&&e.callId!==S||e.seq&&BC.has(e.type)&&!sx(`callapi:${x}:${e.callId}`,e.seq))return!1;if(e.type===`EXECUTION_STATUS_UPDATE`){let t=e.executionLog||[];if(t.length>0&&t.forEach(e=>{let t=d.findIndex(t=>t.id===e.id);t===-1?d.push(e):d[t]={...d[t],...e}}),e.subtaskTotal&&e.subtaskTotal>0){let t=w();if(t){let n=t.querySelector(`.stream-content`);if(n){let t=e.subtaskIndex??0,i=hw(d);i&&[...i.items].sort((e,t)=>e.index-t.index).forEach(r=>{if(r.index===t)return;let a=`.subtask-progress[data-subtask-index="${r.index}"]`;if(n.querySelector(a))return;let o=document.createElement(`div`);o.className=`subtask-progress subtask-progress-pending`,o.dataset.subtaskIndex=r.index,o.innerHTML=gw(r,i.total||e.subtaskTotal),vw(n,o),_w(o)});let a=`.subtask-progress[data-subtask-index="${t}"]`,o=n.querySelector(a),s=o?o.classList.contains(`subtask-expanded`):!1;o||(o=document.createElement(`div`),o.className=`subtask-progress`,o.dataset.subtaskIndex=t,vw(n,o));let c=pw,l=t+1,u=e.subtaskTotal,f=e.subtaskName||``,p=`<span class="subtask-badge">${l}/${u}</span>`,m=mw,h=e.status!==`success`&&e.status!==`failed`,g=d.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),_=cw(g),v=_.total,y=_.success,b=_.failed,x=_.other,S=g.find(e=>e.status===`processing`),C=sw(e.status,y,v),w=i?i.items.find(e=>e.index===t):null,T=w&&w.description?String(w.description).replace(/\s+/g,` `).trim():``,E=d.find(e=>e.subtaskIndex===t&&e.nodeType===`subtask`),D=uw(d,t)?`<span class="subtask-replay-skipped" title="${Me(r(`chatMsg.subtaskReplaySkippedHint`))}">${r(`chatMsg.subtaskReplaySkipped`)}</span>`:``;o.classList.remove(`subtask-progress-pending`);let O=``;e.status===`success`?(O=`<span class="subtask-status-done">${r(`chatMsg.subtaskDone`)}</span>`,o.classList.add(`subtask-progress-done`),o.classList.remove(`subtask-progress-active`)):C===`partial`?(O=`<span class="subtask-status-partial">${r(`chatMsg.subtaskPartial`)}</span>`,o.classList.add(`subtask-progress-failed`),o.classList.remove(`subtask-progress-active`)):e.status===`failed`?(O=`<span class="subtask-status-failed">${r(`chatMsg.subtaskFailed`)}</span>`,o.classList.add(`subtask-progress-failed`),o.classList.remove(`subtask-progress-active`)):(O=`<span class="subtask-status-label"><span class="subtask-spinner"></span>${r(`chatMsg.subtaskExecuting`)}</span>`,o.classList.add(`subtask-progress-active`));let k=``;if(h&&v>0){let e=S?S.nodeType===`tool_exec`?`🔧`:S.nodeType===`api_call`?`📡`:S.nodeType===`reflection`?`🎯`:S.nodeType===`preselect`?`🔍`:`○`:`○`,t=lw(S),n=S?Rf(S):``;k=`<div class="subtask-progress-line">
|
|
1922
|
+
<span class="subtask-current-node"><span class="subtask-current-spinner"></span><span class="node-label">${e} ${t}</span>${n?` <span class="subtask-current-cmd" title="${Me(n)}">${I(n)}</span>`:``}</span>
|
|
1923
1923
|
<span class="subtask-node-stats">
|
|
1924
1924
|
<span class="subtask-stat-total">${v}</span>
|
|
1925
1925
|
<span class="subtask-stat-done${o._nodeFilter===`success`?` subtask-stat-active`:``}" data-node-filter="success" title="${r(`chatMsg.subtaskFilterHint`)}">✓${y}</span>
|
|
@@ -1933,7 +1933,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1933
1933
|
<span class="subtask-stat-fail${o._nodeFilter===`failed`?` subtask-stat-active`:``}" data-node-filter="failed" title="${r(`chatMsg.subtaskFilterHint`)}">✗ ${b}</span>
|
|
1934
1934
|
${x>0?`<span class="subtask-stat-other${o._nodeFilter===`other`?` subtask-stat-active`:``}" data-node-filter="other" title="${r(`chatMsg.subtaskStatOtherHint`)}">⊘ ${x}</span>`:``}
|
|
1935
1935
|
</span>
|
|
1936
|
-
</div>`;else if(e.status===`failed`){let e=E&&E.error?String(E.error).replace(/\s+/g,` `).trim().slice(0,120):``,t=e?`<span class="subtask-fail-reason">${
|
|
1936
|
+
</div>`;else if(e.status===`failed`){let e=E&&E.error?String(E.error).replace(/\s+/g,` `).trim().slice(0,120):``,t=e?`<span class="subtask-fail-reason">${I(r(`chatMsg.subtaskFailReason`,{error:e}))}</span>`:``;k=`<div class="subtask-progress-line failed">
|
|
1937
1937
|
<span>${r(`chatMsg.subtaskPartialFail`,{success:y,total:v,fail:b})}</span>
|
|
1938
1938
|
<span class="subtask-node-stats">
|
|
1939
1939
|
<span class="subtask-stat-done${o._nodeFilter===`success`?` subtask-stat-active`:``}" data-node-filter="success" title="${r(`chatMsg.subtaskFilterHint`)}">✓ ${y}</span>
|
|
@@ -1942,11 +1942,11 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1942
1942
|
</span>${t}
|
|
1943
1943
|
</div>`}}o.innerHTML=`
|
|
1944
1944
|
<div class="subtask-header">
|
|
1945
|
-
${m}${c}${p}<span class="subtask-name" title="${
|
|
1945
|
+
${m}${c}${p}<span class="subtask-name" title="${Me(T)}">${f}</span>${D}${O}
|
|
1946
1946
|
</div>
|
|
1947
1947
|
${k}
|
|
1948
1948
|
<div class="subtask-detail-body"></div>
|
|
1949
|
-
`,s&&o.classList.add(`subtask-expanded`);let A=o.querySelector(`.subtask-detail-body`);o._renderNodes=()=>{if(!A)return;let e=[];T&&e.push(`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${
|
|
1949
|
+
`,s&&o.classList.add(`subtask-expanded`);let A=o.querySelector(`.subtask-detail-body`);o._renderNodes=()=>{if(!A)return;let e=[];T&&e.push(`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${I(T)}</div>`);let n=E&&E.result?String(E.result).trim():``;n&&e.push(`<div class="subtask-detail-result"><span class="subtask-detail-label">${r(`chatMsg.subtaskResultLabel`)}</span>${I(n)}</div>`);let i=d.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),a=fw(i,o._nodeFilter),s=``;i.length>0&&a.length===0?s=`<div class="subtask-node-empty">${I(r(`chatMsg.subtaskFilterEmpty`))}</div>`:a.length>0&&(s=a.map(e=>{let t=e.nodeType===`tool_exec`?`🔧`:e.nodeType===`api_call`?`📡`:e.nodeType===`reflection`?`🎯`:e.nodeType===`preselect`?`🔍`:`○`,n=e.status===`success`?`✓`:e.status===`failed`?`✗`:h?`<span class="subtask-node-spinner"></span>`:`○`,i=e.status===`success`?`done`:e.status===`failed`?`failed`:`processing`,a=e.duration?Be(e.duration):``,o=I(e.nodeName||r(`chatMsg.unknownNode`)),s=``;if(e.nodeType===`tool_exec`){let t=Rf(e);t&&(s=`<span class="subtask-node-cmd" title="${Me(t)}">${I(t)}</span>`)}return`<div class="subtask-node ${i}">
|
|
1950
1950
|
<span class="subtask-node-icon">${t}</span>
|
|
1951
1951
|
<span class="subtask-node-status">${n}</span>
|
|
1952
1952
|
<span class="subtask-node-name">${o}${s}</span>
|
|
@@ -1964,9 +1964,9 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1964
1964
|
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
|
|
1965
1965
|
</svg>
|
|
1966
1966
|
</button>
|
|
1967
|
-
`;let n=t.querySelector(`.streaming-stop-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),LC(n)}),e.appendChild(t)}}}else if(w(aC(x)),eC(Date.now()),YS()&&YS().length>0){let e=w().querySelector(`.message-content`);YS().forEach(t=>{let n=FC(t);e.insertBefore(n,e.firstChild)}),XS(null)}return w().dataset.callId=S,v=``,JS(x,``),QS(Date.now()),nC(``),jS(w()),!1}if(e.type===`STREAM_CHUNK`)return sx(`callapi:${x}:${e.callId}`,e.seq)&&w()&&(v+=e.delta,JS(x,v),w().isConnected&&SC(w(),v)),!1;if(e.type===`STREAM_TOOL_CALL`)return w()||(w(aC(x)),eC(Date.now())),w()&&e.toolCalls?.length>0&&(xC(w(),e.thinkingContent||v),CC(w(),e.toolCalls)),!1;if(e.type===`STREAM_TOOL_RESULT`)return w()&&e.result&&PC(e.result,w()),!1;if(e.type===`AGENT_STREAM`){if(w()&&e.execId){let t=w();DC(t,E),MC(E,t,e)}return!1}if(e.type===`AGENT_STREAM_DONE`){if(e.execId){let t=E.get(e.execId);t&&t.element&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)}return!1}if(e.type===`STREAM_DONE`){if(w()){let e=w().querySelector(`.stream-status`);e&&(b?.enabled?e.textContent=r(`chatMsg.reflectionInProgress`):e.textContent=``)}return!1}if(e.type===`API_COMPLETE`){let t=e.content&&String(e.content).trim()?e.content:r(`chatMsg.emptyModelReply`);w()&&IC(w(),t,e.executionLog||[],e.reflectionScore,e.reasoningContent,e.wasRevised);let n=w(),i=!!n,a=n?n.dataset.htmlContent||n.outerHTML:null,s=n?n.isConnected:!1,c=n?n.dataset.messageId:null;return k(),console.log(`[callApi API_COMPLETE] wasStreamed:`,i,`| message.executionLog entries:`,e.executionLog?.length||0,`| local executionLog entries:`,d.length,`| agent_file entries:`,(e.executionLog||d)?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length||0),o({content:t,executionLog:e.executionLog||d,reflectionScore:e.reflectionScore,wasStreamed:i,wasRevised:e.wasRevised,streamingHtml:a,streamingConnected:s,streamingMsgId:c,budgetEnded:e.budgetEnded===!0}),!1}else if(e.type===`API_ERROR`){let t=w();return t&&t.isConnected&&t.remove(),k(),l({message:e.error,executionLog:e.executionLog||d}),!1}return!1};if(chrome.runtime.onMessage.addListener(ne),T=e=>ne(e),O.removeListener=()=>{chrome.runtime.onMessage.removeListener(ne)},s)i.debug(`[SidePanel] send RESUME_REACT message,sessionId:`,x,`userGuidance:`,c?`"${c.substring(0,50)}..."`:`( no )`,`timeout:`,y),chrome.runtime.sendMessage({type:`RESUME_REACT`,sessionId:x,callId:S,userGuidance:c||``});else{let r=e.some(e=>Array.isArray(e.content)&&e.content.some(e=>e&&e.type===`image_url`));i.debug(`[SidePanel] send CALL_API message,useTools:`,n,`tabId:`,C.currentTabId,`sessionId:`,x,`apiParams:`,a,`timeout:`,y),chrome.runtime.sendMessage({type:`CALL_API`,sessionId:x,messages:e,model:t,useTools:n,tabId:C.currentTabId,apiParams:a,agentId:p,agentToolIds:m,agentSkillIds:h,forcedMcpServerIds:Array.isArray(u)&&u.length>0?u:null,agentMcpExcludedServerIds:g??null,callId:S,imageApiBase:C.enableImageInput&&r&&C.imageApiBase||``,imageApiKey:C.enableImageInput&&r&&C.imageApiKey||``})}})}function Kw(e){try{let t=e.dataset.rawContent||``,n=e.dataset.textContent_||``;if(!n&&!t){
|
|
1967
|
+
`;let n=t.querySelector(`.streaming-stop-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),LC(n)}),e.appendChild(t)}}}else if(w(aC(x)),eC(Date.now()),YS()&&YS().length>0){let e=w().querySelector(`.message-content`);YS().forEach(t=>{let n=FC(t);e.insertBefore(n,e.firstChild)}),XS(null)}return w().dataset.callId=S,v=``,JS(x,``),QS(Date.now()),nC(``),jS(w()),!1}if(e.type===`STREAM_CHUNK`)return sx(`callapi:${x}:${e.callId}`,e.seq)&&w()&&(v+=e.delta,JS(x,v),w().isConnected&&SC(w(),v)),!1;if(e.type===`STREAM_TOOL_CALL`)return w()||(w(aC(x)),eC(Date.now())),w()&&e.toolCalls?.length>0&&(xC(w(),e.thinkingContent||v),CC(w(),e.toolCalls)),!1;if(e.type===`STREAM_TOOL_RESULT`)return w()&&e.result&&PC(e.result,w()),!1;if(e.type===`AGENT_STREAM`){if(w()&&e.execId){let t=w();DC(t,E),MC(E,t,e)}return!1}if(e.type===`AGENT_STREAM_DONE`){if(e.execId){let t=E.get(e.execId);t&&t.element&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)}return!1}if(e.type===`STREAM_DONE`){if(w()){let e=w().querySelector(`.stream-status`);e&&(b?.enabled?e.textContent=r(`chatMsg.reflectionInProgress`):e.textContent=``)}return!1}if(e.type===`API_COMPLETE`){let t=e.content&&String(e.content).trim()?e.content:r(`chatMsg.emptyModelReply`);w()&&IC(w(),t,e.executionLog||[],e.reflectionScore,e.reasoningContent,e.wasRevised);let n=w(),i=!!n,a=n?n.dataset.htmlContent||n.outerHTML:null,s=n?n.isConnected:!1,c=n?n.dataset.messageId:null;return k(),console.log(`[callApi API_COMPLETE] wasStreamed:`,i,`| message.executionLog entries:`,e.executionLog?.length||0,`| local executionLog entries:`,d.length,`| agent_file entries:`,(e.executionLog||d)?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length||0),o({content:t,executionLog:e.executionLog||d,reflectionScore:e.reflectionScore,wasStreamed:i,wasRevised:e.wasRevised,streamingHtml:a,streamingConnected:s,streamingMsgId:c,budgetEnded:e.budgetEnded===!0}),!1}else if(e.type===`API_ERROR`){let t=w();return t&&t.isConnected&&t.remove(),k(),l({message:e.error,executionLog:e.executionLog||d}),!1}return!1};if(chrome.runtime.onMessage.addListener(ne),T=e=>ne(e),O.removeListener=()=>{chrome.runtime.onMessage.removeListener(ne)},s)i.debug(`[SidePanel] send RESUME_REACT message,sessionId:`,x,`userGuidance:`,c?`"${c.substring(0,50)}..."`:`( no )`,`timeout:`,y),chrome.runtime.sendMessage({type:`RESUME_REACT`,sessionId:x,callId:S,userGuidance:c||``});else{let r=e.some(e=>Array.isArray(e.content)&&e.content.some(e=>e&&e.type===`image_url`));i.debug(`[SidePanel] send CALL_API message,useTools:`,n,`tabId:`,C.currentTabId,`sessionId:`,x,`apiParams:`,a,`timeout:`,y),chrome.runtime.sendMessage({type:`CALL_API`,sessionId:x,messages:e,model:t,useTools:n,tabId:C.currentTabId,apiParams:a,agentId:p,agentToolIds:m,agentSkillIds:h,forcedMcpServerIds:Array.isArray(u)&&u.length>0?u:null,agentMcpExcludedServerIds:g??null,callId:S,imageApiBase:C.enableImageInput&&r&&C.imageApiBase||``,imageApiKey:C.enableImageInput&&r&&C.imageApiKey||``})}})}function Kw(e){try{let t=e.dataset.rawContent||``,n=e.dataset.textContent_||``;if(!n&&!t){P(r(`chatMsg.cannotGetMessageContent`),`error`);return}let a=[];if(t.startsWith(`[`))try{let e=JSON.parse(t);if(Array.isArray(e)){let t=e.filter(e=>e.type===`image_url`);for(let e of t){let t=e.image_url.original_url||e.image_url.url;a.push({originalUrl:t,compressedUrl:e.image_url.url,width:e.image_url.width,height:e.image_url.height})}}}catch{}a.length>0&&(C.attachedImages=a,Vp());let o=[];if(e.dataset.attachedFiles)try{let t=JSON.parse(e.dataset.attachedFiles);for(let e of t)o.push({name:e.name,size:e.size,type:e.type,text:e.text||``,status:e.status||`done`,agentPath:e.agentPath||``})}catch{}o.length>0&&(C.attachedFiles=o,A(()=>Promise.resolve().then(()=>lm).then(e=>{e.renderFilePreviews()}),void 0));let s=n.match(/^\[网页上下文\]\n标题: (.+)\nURL: (.+)\ntabId: (\d+)\n/);if(s){nx(),C.selectedPage={id:parseInt(s[3]),title:s[1],url:s[2],favIconUrl:``};let e=document.getElementById(`pageIndicator`),t=document.getElementById(`pageIndicatorName`);if(e&&t){let n=s[1],r=s[2];n&&n!==`无标题`&&r?t.textContent=`${n} · ${r}`:t.textContent=n||r,e.style.display=`flex`}}let c=n.match(/\[知识库检索结果\](引用: ([^)]+))/);if(c){let e=c[1].split(`、`).map(e=>e.trim()).filter(Boolean);e.length>0&&(Vb(),C.knowledgeRefs=e.map(e=>({id:``,name:e})),Hb(),Kb().then(e=>{if(e&&e.ok){let t=new Map((e.collections||[]).map(e=>[e.name,e]));C.knowledgeRefs=C.knowledgeRefs.map(e=>{if(e.id)return e;let n=t.get(e.name);return{id:n?.id||``,name:e.name,enabled:n?n.enabled!==!1:!0}}),Hb()}}).catch(()=>{}))}let l=Array.from(new Set([...n.matchAll(/\[(?:已选技能|Selected skill):\s*([^\n\]]+)\]/g)].map(e=>e[1].split(` - `)[0].trim()).filter(Boolean)));l.length>0&&(OT(),C.selectedSkills=l.map(e=>({name:e,description:``,type:`agent`})),kT());let u=Array.from(new Set([...n.matchAll(/\[(?:已选MCP服务|Selected MCP service):\s*([^\n\]]+)\]/g)].map(e=>e[1].split(` - `)[0].trim()).filter(Boolean)));u.length>0&&(VT(),C.selectedMcpServices=u.map(e=>({serverId:``,serverName:e,toolCount:0})),UT(),chrome.storage.local.get([`mcpTools`],e=>{let t=e.mcpTools||[];u.forEach(e=>{let n=C.selectedMcpServices.find(t=>t.serverName===e);if(!n||n.serverId)return;let r=t.find(t=>(t.serverName||``)===e)||t.find(t=>(t.serverName||``).startsWith(e));r&&(n.serverId=r.serverId||``,n.toolCount=t.filter(e=>e.serverId===r.serverId).length)}),UT()}));let d=n;s&&(d=d.replace(/^\[网页上下文\]\n标题: .+\nURL: .+\ntabId: \d+\n/,``)),c&&(d=d.replace(/\[知识库检索结果\][^\n]*\n[\s\S]*?\[\/知识库检索结果\]\n\n?/,``)),u.length>0&&(d=Ow(d)),l.length>0&&(d=Dw(d));let f=C.quotedContextText,p=C.selectedContextText;C.quotedContextText=``,C.selectedContextText=``;let m=d.match(/^\[引用内容(?:摘要)?\]\n([\s\S]+?)\n\n\[用户问题\]\n([\s\S]*)$/),h=d.match(/^\[选中内容(?:摘要)?\]\n([\s\S]+?)\n\n\[用户问题\]\n([\s\S]*)$/),g=m||h,_=d;if(g){let e=m?`quoted`:`selected`,t=g[1].trim(),n=g[2].trim();if(o.length>0){let e=n.search(/\n\n\[(?:工作目录)?文件(?:内容)?:/);e!==-1&&(n=n.substring(0,e).trim())}let i=document.getElementById(`selectionIndicator`),a=document.getElementById(`selectionText`);if(i&&a){let n;n=t.length>100?t.substring(0,100)+`...`:t.length>50?t.substring(0,50)+`...`:t,e===`quoted`?(C.quotedContextText=t,C.selectedContextText=p,a.textContent=r(`chatMsg.quotedContextLabel`,{text:n})):(C.selectedContextText=t,C.quotedContextText=f,a.textContent=r(`chatMsg.selectedContextLabel`,{text:n})),i.classList.add(`show`)}_=n}else if(C.quotedContextText=f,C.selectedContextText=p,o.length>0){let e=_.search(/\n\n\[(?:工作目录)?文件(?:内容)?:/);e!==-1&&(_=_.substring(0,e).trim())}let v=document.getElementById(`userInput`);v.value=_,lt(),v.focus(),v.selectionStart=v.selectionEnd=v.value.length,i.debug(`[SidePanel] loadedmessagecontent to input box,waitingafter user editsend`)}catch(e){i.error(`[SidePanel] editmessage failed:`,e),P(r(`chatMsg.editFailed`,{message:e.message}),`error`)}}n(`zh`,{promptMgr:{promptsTabCount:`提示词 ({count})`,skillsTabCount:`技能 ({count})`,mcpTabCount:`MCP ({count})`,noMatchPrompt:`暂无匹配的提示词`,mergedHeaderHint:`方向键切换 · Enter发送/选择 · Ctrl+Enter带入/选中并关闭 · Esc取消`,noMatchResult:`暂无匹配结果`,requestFailed:`❌ 请求失败:{message}`,emptyPromptHint:`暂无提示词,请添加`,menuDisplayTitle:`菜单显示`,codeAndContentRequired:`请填写编码和内容`,codeExists:`编码已存在`,saveChanges:`保存修改`,confirmDeletePrompt:`确定要删除提示词 "/{code}" 吗?`}}),n(`en`,{promptMgr:{promptsTabCount:`Prompts ({count})`,skillsTabCount:`Skills ({count})`,mcpTabCount:`MCP ({count})`,noMatchPrompt:`No matching prompts`,mergedHeaderHint:`Arrow keys to switch · Enter to send/select · Ctrl+Enter to insert/select & close · Esc to cancel`,noMatchResult:`No matching results`,requestFailed:`❌ Request failed: {message}`,emptyPromptHint:`No prompts yet, please add one`,menuDisplayTitle:`Show in menu`,codeAndContentRequired:`Please fill in both code and content`,codeExists:`Code already exists`,saveChanges:`Save changes`,confirmDeletePrompt:`Are you sure you want to delete prompt "/{code}"?`}});var qw=`<svg viewBox="0 0 1024 1024" width="12" height="12" fill="currentColor"><path d="M674.56 231.552l101.568 56.96-56.896-101.632 56.96-101.568-101.632 56.896-101.632-56.896 56.96 101.568-56.896 101.632 101.568-56.96zM186.944 629.76l-101.504-56.896 56.832 101.632-56.832 101.568 101.504-56.96 101.632 56.96-56.896-101.568 56.896-101.568-101.568 56.832zM85.44 85.312l56.832 101.568-56.832 101.632 101.504-56.96 101.632 56.96L231.68 186.88l56.896-101.568-101.568 56.896-101.568-56.896z m351.872 438.016l-99.2-99.136L424.32 337.984l99.072 99.264-86.08 86.144m-41.856-223.04L300.352 395.392a40.448 40.448 0 0 0 0 57.28l474.24 474.112a40.448 40.448 0 0 0 57.344 0l94.912-95.04a40.448 40.448 0 0 0 0-57.344L452.736 300.288a40.448 40.448 0 0 0-57.28 0z"/></svg>`;function Jw(){i.debug(`[SidePanel] clear selectedcontenttext `),C.selectedContextText=``,C.quotedContextText=``;let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`userInput`);if(e&&(e.classList.remove(`show`),i.debug(`[SidePanel] hiddenselected contentprompt`)),typeof window.hideFloatingMenu==`function`&&window.hideFloatingMenu(),t&&t.value.startsWith(`[选中内容]`)){let e=t.value.split(`
|
|
1968
1968
|
`),n=0;for(let t=0;t<e.length;t++)if(e[t].startsWith(`[用户问题]`)){n=t;break}n>0&&(t.value=e.slice(n).join(`
|
|
1969
|
-
`),t.dispatchEvent(new Event(`input`)),i.debug(`[SidePanel] removedinput box selected content before suffix`))}C.lastSelectedText=``,C.currentSelectionRange=null}function Yw(){let e=document.getElementById(`promptManageList`).querySelectorAll(`.prompt-manage-item`);e.forEach(t=>{t.addEventListener(`dragstart`,e=>{C.draggedItemIndex=parseInt(t.dataset.index),t.classList.add(`dragging`),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,C.draggedItemIndex)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),e.forEach(e=>e.classList.remove(`drag-over`)),C.draggedItemIndex=null}),t.addEventListener(`dragover`,e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`,t.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drag-over`)}),t.addEventListener(`drop`,e=>{e.stopPropagation(),e.preventDefault();let n=parseInt(t.dataset.index);if(C.draggedItemIndex!==null&&C.draggedItemIndex!==n){let e=C.customPrompts[C.draggedItemIndex];C.customPrompts.splice(C.draggedItemIndex,1),C.customPrompts.splice(n,0,e),chrome.storage.local.set({customPrompts:C.customPrompts}),cT()}t.classList.remove(`drag-over`)})})}function Xw(){let e=document.querySelector(`#promptDropdown .prompt-dropdown-header`);if(!e||e.querySelector(`.prompt-manage-btn`))return;let t=document.createElement(`button`);t.className=`prompt-manage-btn`,t.title=r(`promptManager.title`),t.style.fontSize=`13px`,t.innerHTML=`✚`,t.addEventListener(`click`,e=>{e.stopPropagation(),oT()}),e.appendChild(t)}async function Zw(e=``,t=null){let n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`);
|
|
1969
|
+
`),t.dispatchEvent(new Event(`input`)),i.debug(`[SidePanel] removedinput box selected content before suffix`))}C.lastSelectedText=``,C.currentSelectionRange=null}function Yw(){let e=document.getElementById(`promptManageList`).querySelectorAll(`.prompt-manage-item`);e.forEach(t=>{t.addEventListener(`dragstart`,e=>{C.draggedItemIndex=parseInt(t.dataset.index),t.classList.add(`dragging`),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,C.draggedItemIndex)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),e.forEach(e=>e.classList.remove(`drag-over`)),C.draggedItemIndex=null}),t.addEventListener(`dragover`,e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`,t.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drag-over`)}),t.addEventListener(`drop`,e=>{e.stopPropagation(),e.preventDefault();let n=parseInt(t.dataset.index);if(C.draggedItemIndex!==null&&C.draggedItemIndex!==n){let e=C.customPrompts[C.draggedItemIndex];C.customPrompts.splice(C.draggedItemIndex,1),C.customPrompts.splice(n,0,e),chrome.storage.local.set({customPrompts:C.customPrompts}),cT()}t.classList.remove(`drag-over`)})})}function Xw(){let e=document.querySelector(`#promptDropdown .prompt-dropdown-header`);if(!e||e.querySelector(`.prompt-manage-btn`))return;let t=document.createElement(`button`);t.className=`prompt-manage-btn`,t.title=r(`promptManager.title`),t.style.fontSize=`13px`,t.innerHTML=`✚`,t.addEventListener(`click`,e=>{e.stopPropagation(),oT()}),e.appendChild(t)}async function Zw(e=``,t=null){let n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`);qe(),n.style.display=`block`,r.classList.add(`show`);let i=document.getElementById(`skillsTab`),a=document.getElementById(`mcpTab`),o=i?await xT():!1,s=a?await IT():!1;if(i&&(i.style.display=o?`block`:`none`),a&&(a.style.display=s?`block`:`none`),$w(o,s),e)await nT(e);else{let n=t||C.lastActiveDropdownTab||`prompts`,r=document.querySelector(`#promptDropdownTabs .prompt-tab[data-tab="${n}"]`),i=`prompts`;if(r&&r.style.display!==`none`)i=n;else{let e=document.querySelectorAll(`#promptDropdownTabs .prompt-tab`);for(let t of e)if(t.style.display!==`none`){i=t.dataset.tab;break}}await MT(i),tT(e)}}function Qw(){let e=document.getElementById(`promptSelector`),t=document.getElementById(`promptDropdown`);e.style.display=`none`,t.classList.remove(`show`),C.selectedPromptIndex=-1,C.showMergedList=!1;let n=document.getElementById(`promptDropdownTabs`);n&&n.classList.remove(`merged-mode`)}async function $w(e,t){try{let n=C.customPrompts.length,i=document.querySelector(`#promptDropdownTabs .prompt-tab[data-tab="prompts"]`);if(i&&(i.textContent=r(`promptMgr.promptsTabCount`,{count:n})),e){let e=await CT(),t=document.getElementById(`skillsTab`);t&&(t.textContent=r(`promptMgr.skillsTabCount`,{count:e.length}))}if(t){let e=await LT(),t=document.getElementById(`mcpTab`);t&&(t.textContent=r(`promptMgr.mcpTabCount`,{count:e.length}))}}catch{}}function eT(e=``){e?nT(e):tT(e)}function tT(e=``){let t=document.getElementById(`promptList`),n=e.toLowerCase(),i=C.customPrompts.filter(t=>e?t.code.toLowerCase().includes(n)||t.content.toLowerCase().includes(n):!0);if(i.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptMgr.noMatchPrompt`)}</div>`,C.selectedPromptIndex=-1;return}C.selectedPromptIndex=0,t.innerHTML=i.map((e,t)=>`
|
|
1970
1970
|
<div class="prompt-item ${t===C.selectedPromptIndex?`selected`:``}" data-index="${t}" data-code="${e.code}">
|
|
1971
1971
|
<span class="prompt-item-index">${t+1}</span>
|
|
1972
1972
|
<span class="prompt-item-icon">${qw}</span>
|
|
@@ -1980,24 +1980,24 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1980
1980
|
<span class="prompt-item-content">${e.content}</span>
|
|
1981
1981
|
<span class="prompt-item-code">/${e.code}</span>
|
|
1982
1982
|
</div>`;return g++,t}).join(``),v=f.map(e=>{let t=e.enabled===!1,n=t?`${e.name}\n${r(`skillSelector.disabledTooltip`)}`:e.name,i=`
|
|
1983
|
-
<div class="prompt-item merged-skill-item ${g===0?`selected`:``} ${t?`merged-skill-item-disabled`:``}" data-index="${g}" data-type="skill" data-skill-name="${
|
|
1983
|
+
<div class="prompt-item merged-skill-item ${g===0?`selected`:``} ${t?`merged-skill-item-disabled`:``}" data-index="${g}" data-type="skill" data-skill-name="${I(e.name)}" title="${Me(n)}">
|
|
1984
1984
|
<span class="prompt-item-index">${g+1}</span>
|
|
1985
|
-
<span class="prompt-item-content">🧩 ${
|
|
1985
|
+
<span class="prompt-item-content">🧩 ${I(e.name)}${e.description?` - `+I(e.description):``}</span>
|
|
1986
1986
|
<span class="merged-item-badge badge-skill">${r(`promptSelector.skills`)}</span>
|
|
1987
1987
|
${t?`<span class="merged-item-badge badge-disabled">${r(`skillSelector.disabledBadge`)}</span>`:``}
|
|
1988
1988
|
</div>`;return g++,i}).join(``),y=p.map(e=>{let t=e.effectiveOpen===!1,n=`
|
|
1989
|
-
<div class="prompt-item merged-mcp-item ${g===0?`selected`:``} ${t?`merged-mcp-item-inactive`:``}" data-index="${g}" data-type="mcp" data-server-id="${
|
|
1989
|
+
<div class="prompt-item merged-mcp-item ${g===0?`selected`:``} ${t?`merged-mcp-item-inactive`:``}" data-index="${g}" data-type="mcp" data-server-id="${I(e.serverId)}" data-server-name="${I(e.serverName)}">
|
|
1990
1990
|
<span class="prompt-item-index">${g+1}</span>
|
|
1991
|
-
<span class="prompt-item-content">🔌 ${
|
|
1991
|
+
<span class="prompt-item-content">🔌 ${I(e.serverName)}</span>
|
|
1992
1992
|
${t?`<span class="merged-item-badge badge-mcp-inactive">${r(`skillSelector.mcpInactiveBadge`)}</span>`:``}
|
|
1993
1993
|
<span class="merged-item-badge badge-mcp">MCP</span>
|
|
1994
1994
|
</div>`;return g++,n}).join(``);t.innerHTML=_+v+y,t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=e.dataset.type;if(n===`skill`){let n=e.dataset.skillName;DT(n,await CT()),(t.ctrlKey||t.metaKey)&&Qw()}else if(n===`mcp`){let n=e.dataset.serverId,r=e.dataset.serverName;BT(n,r,await LT()),(t.ctrlKey||t.metaKey)&&Qw()}else{let n=e.dataset.code;t.ctrlKey||t.metaKey?iT(n):aT(n)}})}),AT(),WT()}function rT(e){e.forEach((e,t)=>{t===C.selectedPromptIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function iT(e,{skipTriggerStrip:t=!1}={}){let n=C.customPrompts.find(t=>t.code===e);if(!n)return;let r=document.getElementById(`userInput`),a=r.value,o=a.lastIndexOf(`/`),s=a;if(!t&&o!==-1){let e=-1;for(let t=o-1;t>=0;t--)if(a[t]===`
|
|
1995
1995
|
`){e=t;break}s=e===-1?a.substring(0,o).trimEnd():a.substring(0,e+1).trimEnd()}r.value=s+(s&&!s.endsWith(`
|
|
1996
1996
|
`)?`
|
|
1997
1997
|
|
|
1998
|
-
`:``)+n.content,r.focus(),r.selectionStart=r.selectionEnd=r.value.length,Qw(),
|
|
1998
|
+
`:``)+n.content,r.focus(),r.selectionStart=r.selectionEnd=r.value.length,Qw(),lt(),i.debug(`[SidePanel] trackaddpromptword to input box:`,n.code,n.content)}async function aT(e){let t=C.customPrompts.find(t=>t.code===e);if(!t)return;if(C.isGenerating){i.debug(`[SidePanel] generating,please wait...`);return}let n=document.getElementById(`userInput`)?.value||``,a={quotedContextText:C.quotedContextText||``,selectedContextText:C.selectedContextText||``,selectedSkills:C.selectedSkills.slice(),selectedMcpServices:C.selectedMcpServices.slice(),knowledgeRefs:C.knowledgeRefs.slice(),selectedPage:C.selectedPage,attachedImages:C.attachedImages.slice(),attachedFiles:C.attachedFiles.slice()};await Xc({state:C,getRatio:()=>WE().usage?.ratio??0,compact:$E}),Qw();let o=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);o&&o.remove();let s=t.content,c=a.selectedContextText&&a.selectedContextText.trim(),l=a.quotedContextText&&a.quotedContextText.trim(),u=[];if(l){let e=a.quotedContextText.trim(),{compressed:n,wasCompressed:r}=m(e);s=`[引用内容${r?`摘要`:``}]\n${n}\n\n[用户问题]\n${t.content}`,Ew(`quoted`,e,!1),u.push({type:`quoted`,text:e}),C.quotedContextText===a.quotedContextText&&(C.quotedContextText=``)}else if(c){let e=a.selectedContextText.trim(),{compressed:n,wasCompressed:r}=m(e);s=`[选中内容${r?`摘要`:``}]\n${n}\n\n[用户问题]\n${t.content}`,Ew(`selected`,e,!1),u.push({type:`selected`,text:e}),C.selectedContextText===a.selectedContextText&&(C.selectedContextText=``)}let d=a.selectedSkills,f=await FT(d);if(f){s=f+s;for(let e of d)Ew(`skill`,r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``}),!1),u.push({type:`skill`,name:e.name,description:e.description||``});let e=new Set(d),t=C.selectedSkills.filter(t=>!e.has(t));t.length!==C.selectedSkills.length&&(C.selectedSkills=t,C.selectedSkillIndex=-1,kT(),AT())}let p=null,h=a.selectedMcpServices,_=HT(h);if(_){let e=h.map(e=>e.serverId).filter(Boolean);p=e.length>0?e:null,s=_+s;for(let e of h)Ew(`mcp`,r(`contextBubble.bubbleMcp`,{name:e.serverName}),!1),u.push({type:`mcp`,serverName:e.serverName,serverId:e.serverId||``});let t=new Set(h),n=C.selectedMcpServices.filter(e=>!t.has(e));n.length!==C.selectedMcpServices.length&&(C.selectedMcpServices=n,C.selectedMcpServiceIndex=-1,UT(),WT())}let v=a.knowledgeRefs;if(v.length>0){let e=Ew(`knowledge`,r(`contextBubble.bubbleKnowledgeSearching`),!1),n=null;try{n=await aw(t.content,v)}catch(e){i.warn(`[SidePanel] knowledge search failed:`,e)}e&&e.parentNode&&e.remove(),n&&(s=n.text+s,ow(n.refs,n.failed===!0),u.push({type:`knowledge`,refs:n.refs,failed:n.failed||void 0}));let a=new Set(v),o=C.knowledgeRefs.filter(e=>!a.has(e));o.length!==C.knowledgeRefs.length&&(C.knowledgeRefs=o,Rb(),Hb())}let y=a.selectedPage;y&&(s=`[网页上下文]\n标题: ${y.title}\nURL: ${y.url}\ntabId: ${y.id}\n`+s,Ew(`page`,r(`contextBubble.bubblePage`,{title:y.title,url:y.url}),!1),u.push({type:`page`,title:y.title,url:y.url}),C.selectedPage===y&&nx()),(c||l)&&(!C.quotedContextText&&!C.selectedContextText?Jw():KC());let b=a.attachedFiles,x=(a.attachedImages||[]).slice();if(b.length>0){let e=jm(b);e&&(s+=e),b.forEach(e=>{e.status===`done`&&u.push({type:`file`,name:e.name,size:e.size,fileType:e.type})})}let S=null;if(b.length>0||x.length>0)try{S=await j(C.activeSessionId,b,x)}catch(e){i.warn(`[Prompt] save doc image snapshot failed:`,e.message)}let w=Te(S?.chatStart,S?.chatCount);w&&(s+=w);let T=Hp(s,x),{messageId:E,timestamp:D}=Aw(`user`,Hp(t.content,x),!0,[],null,!1,s,null,b);C.messageHistory.push({role:`user`,content:T,messageId:E,timestamp:D,contextBubbles:u}),$C(),cn(t.content);let O=document.getElementById(`userInput`);O.value===n&&(O.value=``,O.style.height=`auto`),C.isGenerating=!0;let k=Iw(),A=C.activeSessionId,M=C.enableImageInput&&x.length>0&&C.imageModelName||C.currentModel;if(x.length>0){let e=new Set(x),t=C.attachedImages.filter(t=>!e.has(t));t.length!==C.attachedImages.length&&(C.attachedImages=t,Vp())}if(b.length>0){let e=new Set(b),t=C.attachedFiles.filter(t=>!e.has(t));if(t.length!==C.attachedFiles.length){for(let t of C.attachedFiles)e.has(t)&&t.dataUrl&&URL.revokeObjectURL(t.dataUrl);C.attachedFiles=t,Am()}}try{await nt(),i.debug(`[SidePanel] sendmessagedebuginfo:`),i.debug(` - isolateChat:`,C.isolateChat),i.debug(` - chatConfig:`,C.chatConfig),i.debug(` - messageHistory.length:`,C.messageHistory.length);let e=[{role:`system`,content:await Ge(null,{sessionId:A})}];if(C.isolateChat){let t=g(M,C.enabledTools.length||50,0,C.customModelMap),n=Math.floor(t*.7),r=C.messageHistory[C.messageHistory.length-1],a=nn(C.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:C.chatConfig.maxMemoryMessages,compaction:C.activeCompaction,historyBudget:n,currentMessage:r});an(e,a,C.activeCompaction,i),a.historySummaryText&&(e[0]={...e[0],content:e[0].content+`
|
|
1999
1999
|
|
|
2000
|
-
`+a.historySummaryText}),e=[...e,...a.messages];for(let t=0;t<e.length-1;t++)e[t]={...e[t],content:Up(e[t].content)}}else e.push({role:`user`,content:T});let n=await
|
|
2000
|
+
`+a.historySummaryText}),e=[...e,...a.messages];for(let t=0;t<e.length-1;t++)e[t]={...e[t],content:Up(e[t].content)}}else e.push({role:`user`,content:T});let n=await Ne(),a,o,s=!1,c=null,l=null;try{let t=await Gw(e,M,C.useTools,n,{forcedMcpServerIds:p});a=t.content,o=t.executionLog||[],s=t.wasStreamed||!1,c=t.streamingHtml||null,t.streamingConnected!==void 0&&t.streamingConnected,l=t.streamingMsgId||null}catch(e){Lw(k),a=r(`promptMgr.requestFailed`,{message:e.message||r(`agentConfig.unknownError`)}),o=e.executionLog||[];let{element:n,messageId:i}=Aw(`assistant`,a,!0,o);throw C.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:i}),$C(),e.message!==r(`chatMsg.errTaskStopped`)&&Ol(A,a,t.content),e}let u=null;if(!s||!c)if(Lw(k),s)u=l;else{let{element:e,messageId:t}=Aw(`assistant`,a,!0,o);u=t,await ct(e)}else u=l;C.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:u}),$C(),Dl(A,t.content)}catch{}finally{jl(A),O.focus()}}function oT(){document.getElementById(`promptManageModal`).classList.add(`show`),cT()}function sT(){document.getElementById(`promptManageModal`).classList.remove(`show`);let e=document.getElementById(`editPromptIndex`),t=document.getElementById(`newPromptCode`),n=document.getElementById(`newPromptContent`),i=document.getElementById(`promptManageAddBtn`);e&&(e.value=``),t&&(t.value=``),n&&(n.value=``),i&&(i.textContent=r(`promptManager.addPrompt`),i.style.background=`var(--brand-500)`)}function cT(){let e=document.getElementById(`promptManageList`);if(C.customPrompts.length===0){e.innerHTML=`<div class="prompt-empty">${r(`promptMgr.emptyPromptHint`)}</div>`;return}e.innerHTML=C.customPrompts.map((e,t)=>`
|
|
2001
2001
|
<div class="prompt-manage-item" draggable="true" data-index="${t}">
|
|
2002
2002
|
<div class="prompt-manage-item-left">
|
|
2003
2003
|
<span class="prompt-drag-handle" title="${r(`toolbar.dragSort`)}">⋮⋮</span>
|
|
@@ -2034,40 +2034,40 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
2034
2034
|
`,selectedMcpContext:`[Selected MCP service: {name}]
|
|
2035
2035
|
Please use the "{name}" MCP service to handle the following problem:
|
|
2036
2036
|
`,disabledBadge:`Disabled`,disabledTooltip:`Not enabled (won't be auto-injected into the AI prompt), but you can still select and use it manually`,mcpInactiveBadge:`Inactive`,mcpInactiveTooltip:`This service is currently inactive (closed or excluded by the current agent). Selecting it will force-enable it for this request.`,manualUseSuffix:`Manual`}});var _T=[],vT=0,yT=3e4;async function bT(e=!1){let t=Date.now();return!e&&_T.length>0&&t-vT<yT?_T:new Promise(e=>{chrome.runtime.sendMessage({type:`GET_SKILL_LIST`},t=>{if(chrome.runtime.lastError||!t?.success){e(_T);return}_T=t.skills||[],vT=Date.now(),e(_T)})})}async function xT(){if(!C.agentPlatform?.connected||(await new Promise(e=>{chrome.storage.local.get([`skillsEnabled`],e)})).skillsEnabled===!1)return!1;try{return(await CT()).length>0}catch{return!1}}async function ST(e=!1){return(await bT(e)).filter(e=>e.enabled!==!1)}async function CT(e=!1){let t=[...await bT(e)];return t.sort((e,t)=>(e.enabled===!1)-+(t.enabled===!1)),t}async function wT(e=``){let t=document.getElementById(`skillList`);if(!t)return;let n=await CT(!0),i=e.toLowerCase(),a=n.filter(t=>e?(t.name||``).toLowerCase().includes(i)||(t.description||``).toLowerCase().includes(i):!0);if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchSkill`)}</div>`,C.selectedSkillIndex=-1;return}C.selectedSkillIndex=0,t.innerHTML=a.map((e,t)=>{let n=e.type===`agent`?`Agent`:`Workflow`,i=e.description||``,a=e.enabled===!1,o=a?`${e.name}\n${r(`skillSelector.disabledTooltip`)}`:e.name;return`
|
|
2037
|
-
<div class="skill-list-item ${t===0?`selected`:``} ${a?`skill-list-item-disabled`:``}" data-index="${t}" data-skill-name="${
|
|
2037
|
+
<div class="skill-list-item ${t===0?`selected`:``} ${a?`skill-list-item-disabled`:``}" data-index="${t}" data-skill-name="${I(e.name)}" title="${Me(o)}">
|
|
2038
2038
|
<span class="skill-list-item-index">${t+1}</span>
|
|
2039
2039
|
<span class="skill-list-item-icon">🧩</span>
|
|
2040
2040
|
<div class="skill-list-item-info">
|
|
2041
|
-
<div class="skill-list-item-name">${
|
|
2042
|
-
${i?`<div class="skill-list-item-desc" title="${
|
|
2041
|
+
<div class="skill-list-item-name">${I(e.name)}</div>
|
|
2042
|
+
${i?`<div class="skill-list-item-desc" title="${Me(i)}">${I(i)}</div>`:``}
|
|
2043
2043
|
</div>
|
|
2044
2044
|
<span class="skill-list-item-badge">${n}</span>
|
|
2045
2045
|
${a?`<span class="skill-list-item-badge badge-disabled">${r(`skillSelector.disabledBadge`)}</span>`:``}
|
|
2046
2046
|
</div>
|
|
2047
|
-
`}).join(``),t.querySelectorAll(`.skill-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.skillName;DT(r,n),(t.ctrlKey||t.metaKey)&&Qw()})}),AT()}function TT(e){e.forEach((e,t)=>{t===C.selectedSkillIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function ET(){let e=document.getElementById(`userInput`);if(!e)return;let t=e.value,n=t.lastIndexOf(`/`);n!==-1&&(e.value=t.substring(0,n)),e.focus(),e.selectionStart=e.selectionEnd=e.value.length,
|
|
2047
|
+
`}).join(``),t.querySelectorAll(`.skill-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.skillName;DT(r,n),(t.ctrlKey||t.metaKey)&&Qw()})}),AT()}function TT(e){e.forEach((e,t)=>{t===C.selectedSkillIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function ET(){let e=document.getElementById(`userInput`);if(!e)return;let t=e.value,n=t.lastIndexOf(`/`);n!==-1&&(e.value=t.substring(0,n)),e.focus(),e.selectionStart=e.selectionEnd=e.value.length,lt()}function DT(e,t,{clearTrigger:n=!0}={}){let r=t.find(t=>t.name===e);if(!r)return;let a=C.selectedSkills.findIndex(t=>t.name===e);if(a>=0?C.selectedSkills.splice(a,1):C.selectedSkills.push({name:r.name,description:r.description||``,type:r.type||`agent`,stepCount:r.stepCount||0,parameters:r.parameters||{},enabled:r.enabled!==!1}),AT(),kT(),n)ET();else{let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length),lt()}i.debug(`[SidePanel] skill toggled:`,r.name,`count:`,C.selectedSkills.length)}function OT(){C.selectedSkills=[],C.selectedSkillIndex=-1,kT(),AT(),i.debug(`[SidePanel] skill clearedselect`)}function kT(){let e=document.getElementById(`skillIndicator`);if(e){if(C.selectedSkills.length===0){e.style.display=`none`,e.innerHTML=``;return}e.innerHTML=C.selectedSkills.map(e=>{let t=e.enabled===!1,n=t?`${e.name} (${r(`skillSelector.manualUseSuffix`)})`:e.name,i=t?r(`skillSelector.disabledTooltip`):e.name;return`
|
|
2048
2048
|
<span class="ref-chip skill-ref-chip${t?` skill-ref-chip-manual`:``}">
|
|
2049
|
-
<span class="ref-chip-name" title="${
|
|
2050
|
-
<button class="ref-chip-close" data-skill-name="${
|
|
2049
|
+
<span class="ref-chip-name" title="${Me(i)}">🧩 ${I(n)}</span>
|
|
2050
|
+
<button class="ref-chip-close" data-skill-name="${Me(e.name)}" title="${r(`common.delete`)}">✕</button>
|
|
2051
2051
|
</span>
|
|
2052
2052
|
`}).join(``),e.querySelectorAll(`.ref-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),C.selectedSkills=C.selectedSkills.filter(t=>t.name!==e.dataset.skillName),kT(),AT()})}),e.style.display=`flex`}}function AT(){let e=new Set(C.selectedSkills.map(e=>e.name));document.querySelectorAll(`.skill-list-item, .merged-skill-item`).forEach(t=>{t.classList.toggle(`picked`,e.has(t.dataset.skillName))})}function jT(){let e=document.getElementById(`skillIndicatorClose`);e&&e.addEventListener(`click`,OT)}async function MT(e){C.activeDropdownTab=e,C.lastActiveDropdownTab=e,C.showMergedList=!1;let t=document.getElementById(`promptList`),n=document.getElementById(`skillList`),i=document.getElementById(`mcpList`),a=document.getElementById(`promptDropdownTabs`),o=document.querySelectorAll(`#promptDropdownTabs .prompt-tab`),s=document.querySelector(`#promptDropdownHeader .prompt-dropdown-header-text`);a&&a.classList.remove(`merged-mode`),o.forEach(t=>{t.classList.toggle(`active`,t.dataset.tab===e)}),e===`skills`?(t&&(t.style.display=`none`),n&&(n.style.display=`block`),i&&(i.style.display=`none`),s&&(s.textContent=r(`promptSelector.switchHintSelect`)),C.selectedPromptIndex=-1,C.selectedMcpServiceIndex=-1,await wT()):e===`mcp`?(t&&(t.style.display=`none`),n&&(n.style.display=`none`),i&&(i.style.display=`block`),s&&(s.textContent=r(`promptSelector.switchHintSelect`)),C.selectedPromptIndex=-1,C.selectedSkillIndex=-1,await RT()):(t&&(t.style.display=`block`),n&&(n.style.display=`none`),i&&(i.style.display=`none`),s&&(s.textContent=r(`promptSelector.switchHint`)),C.selectedSkillIndex=-1,C.selectedMcpServiceIndex=-1);let c=document.querySelector(`#promptDropdownHeader .prompt-manage-btn`),l=document.querySelector(`#promptDropdownHeader .skill-manage-btn`),u=document.querySelector(`#promptDropdownHeader .mcp-manage-btn`);c&&(c.style.display=e===`prompts`?``:`none`),l&&(l.style.display=e===`skills`?``:`none`),u&&(u.style.display=e===`mcp`?``:`none`);let d=document.getElementById(`userInput`);d&&d.focus()}function NT(){let e=document.getElementById(`promptDropdownHeader`);if(!e||e.querySelector(`.skill-manage-btn`))return;let t=document.createElement(`button`);t.className=`skill-manage-btn`,t.title=r(`promptSelector.skillManageTitle`),t.style.display=`none`,t.style.fontSize=`13px`,t.innerHTML=`✚`,t.addEventListener(`click`,e=>{e.stopPropagation(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`toolbox`})}),e.appendChild(t)}function PT(){let e=document.getElementById(`promptDropdownTabs`);e&&(NT(),KT(),e.addEventListener(`click`,e=>{let t=e.target.closest(`.prompt-tab`);if(!t)return;let n=t.dataset.tab;n!==C.activeDropdownTab&&MT(n)}))}async function FT(e){let t=e||C.selectedSkills||[];if(t.length===0)return``;let n=[];for(let e of t){let t=e.type===`agent`,i=r(`skillSelector.selectedSkillStart`,{name:e.name});if(e.description&&(i+=` - ${e.description}`),i+=`]
|
|
2053
2053
|
`,t)try{let t=await new Promise(t=>{chrome.runtime.sendMessage({type:`GET_AGENT_SKILL_PROMPT`,name:e.name},e=>{if(chrome.runtime.lastError||!e?.success){t(null);return}t(e)})});t&&t.prompt?i+=`${t.prompt}\n\n${r(`skillSelector.useSkillToolsHint`)}`:i+=r(`skillSelector.loadSkillHint`,{name:e.name})}catch{i+=r(`skillSelector.loadSkillHint`,{name:e.name})}else{i+=r(`skillSelector.runSkillHint`,{name:e.name});let t=e.parameters;if(t&&t.properties&&Object.keys(t.properties).length>0){let e=t.required||[],n=Object.entries(t.properties).map(([t,n])=>r(`skillSelector.paramItem`,{flag:e.includes(t)?r(`skillSelector.requiredParam`):r(`skillSelector.optionalParam`),type:n.type||`string`,desc:n.description||``})).join(r(`skillSelector.paramJoin`));i+=r(`skillSelector.callParamsPrefix`)+n}i+=r(`skillSelector.sentenceEnd`)}n.push(i)}return n.join(`
|
|
2054
2054
|
|
|
2055
2055
|
`)}async function IT(){return!C.agentPlatform?.connected||!await new Promise(e=>{chrome.storage.local.get([`mcpEnabled`],t=>e(t.mcpEnabled))})?!1:(await LT()).length>0}async function LT(){return new Promise(e=>{chrome.storage.local.get([`mcpTools`],t=>{let n=t.mcpTools||[],r=new Set(Array.isArray(C.mcpClosedServers)?C.mcpClosedServers:[]),i=new Set(Array.isArray(C.activeAgentMcpExcludedServerIds)?C.activeAgentMcpExcludedServerIds:[]),a=new Map;n.forEach(e=>{let t=e.serverId||`unknown`;a.has(t)||a.set(t,{serverId:t,serverName:e.serverName||t,toolCount:0,effectiveOpen:!r.has(t)&&!i.has(t)}),a.get(t).toolCount++});let o=Array.from(a.values());e([...o.filter(e=>e.effectiveOpen),...o.filter(e=>!e.effectiveOpen)])})})}async function RT(e=``){let t=document.getElementById(`mcpList`);if(!t)return;let n=await LT(),i=e.toLowerCase(),a=n.filter(t=>e?(t.serverName||``).toLowerCase().includes(i)||(t.serverId||``).toLowerCase().includes(i):!0);if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchMcp`)}</div>`,C.selectedMcpServiceIndex=-1;return}C.selectedMcpServiceIndex=0,t.innerHTML=a.map((e,t)=>{let n=e.effectiveOpen===!1,i=n?`${e.serverName}\n${r(`skillSelector.mcpInactiveTooltip`)}`:e.serverName;return`
|
|
2056
|
-
<div class="mcp-list-item ${t===0?`selected`:``} ${n?`mcp-list-item-inactive`:``}" data-index="${t}" data-server-id="${
|
|
2056
|
+
<div class="mcp-list-item ${t===0?`selected`:``} ${n?`mcp-list-item-inactive`:``}" data-index="${t}" data-server-id="${I(e.serverId)}" data-server-name="${I(e.serverName)}" title="${Me(i)}">
|
|
2057
2057
|
<span class="mcp-list-item-index">${t+1}</span>
|
|
2058
2058
|
<span class="mcp-list-item-icon">🔌</span>
|
|
2059
2059
|
<div class="mcp-list-item-info">
|
|
2060
|
-
<div class="mcp-list-item-name">${
|
|
2061
|
-
<div class="mcp-list-item-desc">${
|
|
2060
|
+
<div class="mcp-list-item-name">${I(e.serverName)}</div>
|
|
2061
|
+
<div class="mcp-list-item-desc">${I(e.serverId)}</div>
|
|
2062
2062
|
</div>
|
|
2063
2063
|
${n?`<span class="mcp-list-item-badge mcp-badge-inactive">${r(`skillSelector.mcpInactiveBadge`)}</span>`:``}
|
|
2064
2064
|
<span class="mcp-list-item-badge">${r(`promptSelector.toolCount`,{count:e.toolCount})}</span>
|
|
2065
2065
|
</div>
|
|
2066
|
-
`}).join(``),t.querySelectorAll(`.mcp-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.serverId,i=e.dataset.serverName;BT(r,i,n),(t.ctrlKey||t.metaKey)&&Qw()})}),WT()}function zT(e){e.forEach((e,t)=>{t===C.selectedMcpServiceIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function BT(e,t,n,{clearTrigger:r=!0}={}){let a=n?.find(t=>t.serverId===e)?.toolCount||0,o=t||e,s=C.selectedMcpServices.findIndex(e=>e.serverName===o);if(s>=0?C.selectedMcpServices.splice(s,1):C.selectedMcpServices.push({serverId:e,serverName:o,toolCount:a}),WT(),UT(),r)ET();else{let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length),
|
|
2066
|
+
`}).join(``),t.querySelectorAll(`.mcp-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.serverId,i=e.dataset.serverName;BT(r,i,n),(t.ctrlKey||t.metaKey)&&Qw()})}),WT()}function zT(e){e.forEach((e,t)=>{t===C.selectedMcpServiceIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function BT(e,t,n,{clearTrigger:r=!0}={}){let a=n?.find(t=>t.serverId===e)?.toolCount||0,o=t||e,s=C.selectedMcpServices.findIndex(e=>e.serverName===o);if(s>=0?C.selectedMcpServices.splice(s,1):C.selectedMcpServices.push({serverId:e,serverName:o,toolCount:a}),WT(),UT(),r)ET();else{let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length),lt()}i.debug(`[SidePanel] MCP service toggled:`,o,`count:`,C.selectedMcpServices.length)}function VT(){C.selectedMcpServices=[],C.selectedMcpServiceIndex=-1,UT(),WT(),i.debug(`[SidePanel] cleared MCP serviceselect`)}function HT(e){let t=e||C.selectedMcpServices||[];return t.length===0?``:t.map(e=>r(`skillSelector.selectedMcpContext`,{name:e.serverName})).join(`
|
|
2067
2067
|
`)}function UT(){let e=document.getElementById(`mcpIndicator`);if(e){if(C.selectedMcpServices.length===0){e.style.display=`none`,e.innerHTML=``;return}e.innerHTML=C.selectedMcpServices.map(e=>`
|
|
2068
2068
|
<span class="ref-chip mcp-ref-chip">
|
|
2069
|
-
<span class="ref-chip-name" title="${
|
|
2070
|
-
<button class="ref-chip-close" data-server-name="${
|
|
2069
|
+
<span class="ref-chip-name" title="${Me(e.serverName)}">🔌 ${I(e.serverName)}</span>
|
|
2070
|
+
<button class="ref-chip-close" data-server-name="${Me(e.serverName)}" title="${r(`common.delete`)}">✕</button>
|
|
2071
2071
|
</span>
|
|
2072
2072
|
`).join(``),e.querySelectorAll(`.ref-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),C.selectedMcpServices=C.selectedMcpServices.filter(t=>t.serverName!==e.dataset.serverName),UT(),WT()})}),e.style.display=`flex`}}function WT(){let e=new Set(C.selectedMcpServices.map(e=>e.serverName));document.querySelectorAll(`.mcp-list-item, .merged-mcp-item`).forEach(t=>{t.classList.toggle(`picked`,e.has(t.dataset.serverName))})}function GT(){let e=document.getElementById(`mcpIndicatorClose`);e&&e.addEventListener(`click`,VT)}function KT(){let e=document.getElementById(`promptDropdownHeader`);if(!e||e.querySelector(`.mcp-manage-btn`))return;let t=document.createElement(`button`);t.className=`mcp-manage-btn`,t.title=r(`promptSelector.mcpManageTitle`),t.style.display=`none`,t.style.fontSize=`13px`,t.innerHTML=`✚`,t.addEventListener(`click`,e=>{e.stopPropagation(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`toolbox`})}),e.appendChild(t)}var qT=[[`🀄`,`mahjong tile red dragon`,`symbols`,`麻将,红中`],[`🃏`,`playing card black joker`,`symbols`,``],[`🅰`,`negative squared latin capital letter a`,`symbols`,``],[`🅱`,`negative squared latin capital letter b`,`symbols`,``],[`🅾`,`negative squared latin capital letter o`,`symbols`,``],[`🅿`,`negative squared latin capital letter p`,`symbols`,``],[`🆎`,`negative squared ab`,`symbols`,``],[`🆑`,`squared cl`,`symbols`,``],[`🆒`,`squared cool`,`symbols`,``],[`🆓`,`squared free`,`symbols`,``],[`🆔`,`squared id`,`symbols`,``],[`🆕`,`squared new`,`symbols`,``],[`🆖`,`squared ng`,`symbols`,``],[`🆗`,`squared ok`,`symbols`,``],[`🆘`,`squared sos`,`symbols`,``],[`🆙`,`squared up with exclamation mark`,`symbols`,``],[`🆚`,`squared vs`,`symbols`,``],[`🇨🇩`,`regional indicator symbol letter c`,`flags`,``],[`🇬🇭`,`regional indicator symbol letter g`,`flags`,``],[`🇲🇳`,`regional indicator symbol letter m`,`flags`,``],[`🇷🇸`,`regional indicator symbol letter r`,`flags`,``],[`🈁`,`squared katakana koko`,`symbols`,``],[`🈂`,`squared katakana sa`,`symbols`,``],[`🈚`,`squared cjk unified ideograph-7121`,`symbols`,``],[`🈯`,`squared cjk unified ideograph-6307`,`symbols`,``],[`🈲`,`squared cjk unified ideograph-7981`,`symbols`,``],[`🈳`,`squared cjk unified ideograph-7a7a`,`symbols`,``],[`🈴`,`squared cjk unified ideograph-5408`,`symbols`,``],[`🈵`,`squared cjk unified ideograph-6e80`,`symbols`,``],[`🈶`,`squared cjk unified ideograph-6709`,`symbols`,``],[`🈷`,`squared cjk unified ideograph-6708`,`symbols`,``],[`🈸`,`squared cjk unified ideograph-7533`,`symbols`,``],[`🈹`,`squared cjk unified ideograph-5272`,`symbols`,``],[`🈺`,`squared cjk unified ideograph-55b6`,`symbols`,``],[`🉐`,`circled ideograph advantage`,`symbols`,``],[`🉑`,`circled ideograph accept`,`symbols`,``],[`🌀`,`cyclone`,`symbols`,`台风,龙卷风,旋风`],[`🌁`,`foggy`,`symbols`,`雾,雾霾,朦胧`],[`🌂`,`closed umbrella`,`symbols`,``],[`🌃`,`night with stars`,`symbols`,`夜晚,星空,城市`],[`🌄`,`sunrise over mountains`,`symbols`,`日出,山,早晨`],[`🌅`,`sunrise`,`symbols`,`日出,太阳,早晨`],[`🌆`,`cityscape at dusk`,`symbols`,`黄昏,傍晚,城市`],[`🌇`,`sunset over buildings`,`symbols`,`日落,黄昏`],[`🌈`,`rainbow`,`symbols`,`彩虹,雨后`],[`🌉`,`bridge at night`,`symbols`,`桥,大桥`],[`🌊`,`water wave`,`symbols`,`海浪,波浪,海`],[`🌋`,`volcano`,`symbols`,`火山,爆发`],[`🌌`,`milky way`,`symbols`,``],[`🌍`,`earth globe europe-africa`,`symbols`,``],[`🌎`,`earth globe americas`,`symbols`,`地球,美洲`],[`🌏`,`earth globe asia-australia`,`symbols`,`地球,亚洲`],[`🌐`,`globe with meridians`,`symbols`,``],[`🌑`,`new moon symbol`,`symbols`,``],[`🌒`,`waxing crescent moon symbol`,`symbols`,``],[`🌓`,`first quarter moon symbol`,`symbols`,``],[`🌔`,`waxing gibbous moon symbol`,`symbols`,``],[`🌕`,`full moon symbol`,`symbols`,``],[`🌖`,`waning gibbous moon symbol`,`symbols`,``],[`🌗`,`last quarter moon symbol`,`symbols`,``],[`🌘`,`waning crescent moon symbol`,`symbols`,``],[`🌙`,`crescent moon`,`symbols`,``],[`🌚`,`new moon with face`,`symbols`,``],[`🌛`,`first quarter moon with face`,`symbols`,``],[`🌜`,`last quarter moon with face`,`symbols`,``],[`🌝`,`full moon with face`,`symbols`,``],[`🌞`,`sun with face`,`symbols`,``],[`🌟`,`glowing star`,`symbols`,`星星,闪光,闪耀`],[`🌠`,`shooting star`,`symbols`,``],[`🌡`,`thermometer`,`symbols`,``],[`🌤`,`white sun with small cloud`,`symbols`,``],[`🌥`,`white sun behind cloud`,`symbols`,``],[`🌦`,`white sun behind cloud with rain`,`symbols`,``],[`🌧`,`cloud with rain`,`symbols`,``],[`🌨`,`cloud with snow`,`symbols`,``],[`🌩`,`cloud with lightning`,`symbols`,``],[`🌪`,`cloud with tornado`,`symbols`,``],[`🌫`,`fog`,`symbols`,``],[`🌬`,`wind blowing face`,`symbols`,``],[`🌭`,`hot dog`,`food`,`热狗`],[`🌮`,`taco`,`food`,`墨西哥卷饼`],[`🌯`,`burrito`,`food`,`墨西哥卷,卷饼`],[`🌰`,`chestnut`,`food`,`栗子,坚果`],[`🌱`,`seedling`,`food`,``],[`🌲`,`evergreen tree`,`food`,`松树,树`],[`🌳`,`deciduous tree`,`food`,`树,大树`],[`🌴`,`palm tree`,`food`,`棕榈树,热带,度假`],[`🌵`,`cactus`,`food`,`仙人掌,沙漠`],[`🌶`,`hot pepper`,`food`,``],[`🌷`,`tulip`,`food`,`郁金香,花`],[`🌸`,`cherry blossom`,`food`,`樱花,花,春天`],[`🌹`,`rose`,`food`,`玫瑰,花,爱情`],[`🌺`,`hibiscus`,`food`,`花,芙蓉`],[`🌻`,`sunflower`,`food`,`向日葵,花,太阳`],[`🌼`,`blossom`,`food`,`雏菊,花`],[`🌽`,`ear of maize`,`food`,`玉米`],[`🌾`,`ear of rice`,`food`,``],[`🌿`,`herb`,`food`,`草,植物,草药`],[`🍀`,`four leaf clover`,`food`,`四叶草,幸运,好运`],[`🍁`,`maple leaf`,`food`,`枫叶,秋天,红叶`],[`🍂`,`fallen leaf`,`food`,`落叶,秋天`],[`🍃`,`leaf fluttering in wind`,`food`,`树叶,风`],[`🍄`,`mushroom`,`food`,`蘑菇,菌`],[`🍅`,`tomato`,`food`,`番茄,西红柿`],[`🍆`,`aubergine`,`food`,`茄子`],[`🍇`,`grapes`,`food`,`葡萄`],[`🍈`,`melon`,`food`,`哈密瓜,甜瓜`],[`🍉`,`watermelon`,`food`,`西瓜`],[`🍊`,`tangerine`,`food`,`橙子,橘子`],[`🍋`,`lemon`,`food`,`柠檬`],[`🍌`,`banana`,`food`,`香蕉`],[`🍍`,`pineapple`,`food`,`菠萝`],[`🍎`,`red apple`,`food`,`苹果`],[`🍏`,`green apple`,`food`,``],[`🍐`,`pear`,`food`,`梨`],[`🍑`,`peach`,`food`,`桃子,蜜桃`],[`🍒`,`cherries`,`food`,`樱桃,车厘子`],[`🍓`,`strawberry`,`food`,`草莓`],[`🍔`,`hamburger`,`food`,`汉堡,汉堡包`],[`🍕`,`slice of pizza`,`food`,`披萨,比萨`],[`🍖`,`meat on bone`,`food`,`骨头,肉,排骨`],[`🍗`,`poultry leg`,`food`,`鸡腿,炸鸡`],[`🍘`,`rice cracker`,`food`,`米饼,仙贝`],[`🍙`,`rice ball`,`food`,`饭团`],[`🍚`,`cooked rice`,`food`,`米饭,饭`],[`🍛`,`curry and rice`,`food`,`咖喱,咖喱饭`],[`🍜`,`steaming bowl`,`food`,`面条,拉面,面`],[`🍝`,`spaghetti`,`food`,`意大利面,意面`],[`🍞`,`bread`,`food`,`面包`],[`🍟`,`french fries`,`food`,`薯条,炸薯条`],[`🍠`,`roasted sweet potato`,`food`,`红薯,地瓜`],[`🍡`,`dango`,`food`,`团子,丸子`],[`🍢`,`oden`,`food`,`关东煮,串`],[`🍣`,`sushi`,`food`,`寿司,三文鱼`],[`🍤`,`fried shrimp`,`food`,`炸虾,天妇罗`],[`🍥`,`fish cake with swirl design`,`food`,`鱼板,鸣门卷`],[`🍦`,`soft ice cream`,`food`,`冰淇淋,甜筒`],[`🍧`,`shaved ice`,`food`,`刨冰,冰沙`],[`🍨`,`ice cream`,`food`,`冰淇淋,圣代`],[`🍩`,`doughnut`,`food`,``],[`🍪`,`cookie`,`food`,``],[`🍫`,`chocolate bar`,`food`,`巧克力`],[`🍬`,`candy`,`food`,`糖果,糖`],[`🍭`,`lollipop`,`food`,`棒棒糖`],[`🍮`,`custard`,`food`,`布丁,焦糖`],[`🍯`,`honey pot`,`food`,`蜂蜜,蜜`],[`🍰`,`shortcake`,`food`,`蛋糕,奶油蛋糕`],[`🍱`,`bento box`,`food`,`便当,盒饭`],[`🍲`,`pot of food`,`food`,`火锅,汤锅,炖菜`],[`🍳`,`cooking`,`food`,`煎蛋,鸡蛋`],[`🍴`,`fork and knife`,`food`,`刀叉,餐具`],[`🍵`,`teacup without handle`,`food`,`绿茶,茶,抹茶`],[`🍶`,`sake bottle and cup`,`food`,`清酒,日本酒`],[`🍷`,`wine glass`,`food`,`红酒,葡萄酒,酒`],[`🍸`,`cocktail glass`,`food`,`鸡尾酒,马提尼`],[`🍹`,`tropical drink`,`food`,`果汁,鸡尾酒`],[`🍺`,`beer mug`,`food`,`啤酒,啤酒杯`],[`🍻`,`clinking beer mugs`,`food`,`干杯,碰杯,啤酒`],[`🍼`,`baby bottle`,`food`,`奶瓶,婴儿,奶粉`],[`🍽`,`fork and knife with plate`,`food`,``],[`🍾`,`bottle with popping cork`,`food`,`香槟,起泡酒,庆祝`],[`🍿`,`popcorn`,`food`,``],[`🎀`,`ribbon`,`activity`,`蝴蝶结,礼物,装饰`],[`🎁`,`wrapped present`,`activity`,`礼物,礼盒,生日`],[`🎂`,`birthday cake`,`activity`,`生日蛋糕,生日,蛋糕`],[`🎃`,`jack-o-lantern`,`activity`,``],[`🎄`,`christmas tree`,`activity`,``],[`🎅`,`father christmas`,`activity`,`圣诞老人,圣诞,圣诞节`],[`🎆`,`fireworks`,`activity`,``],[`🎇`,`firework sparkler`,`activity`,``],[`🎈`,`balloon`,`activity`,`气球,庆祝,派对`],[`🎉`,`party popper`,`activity`,`彩带,庆祝,派对,欢呼`],[`🎊`,`confetti ball`,`activity`,`庆祝`],[`🎋`,`tanabata tree`,`activity`,``],[`🎌`,`crossed flags`,`flags`,`旗,日本,交叉旗`],[`🎍`,`pine decoration`,`activity`,``],[`🎎`,`japanese dolls`,`activity`,`人偶,日本人偶`],[`🎏`,`carp streamer`,`activity`,`鲤鱼旗,日本,端午节`],[`🎐`,`wind chime`,`activity`,`风铃,夏天`],[`🎑`,`moon viewing ceremony`,`activity`,``],[`🎒`,`school satchel`,`activity`,`书包,背包`],[`🎓`,`graduation cap`,`activity`,`学士帽,毕业,学位`],[`🎖`,`military medal`,`activity`,``],[`🎗`,`reminder ribbon`,`activity`,``],[`🎙`,`studio microphone`,`activity`,``],[`🎚`,`level slider`,`activity`,``],[`🎛`,`control knobs`,`activity`,``],[`🎞`,`film frames`,`activity`,``],[`🎟`,`admission tickets`,`activity`,``],[`🎠`,`carousel horse`,`activity`,`旋转木马,游乐园`],[`🎡`,`ferris wheel`,`activity`,`摩天轮,游乐园`],[`🎢`,`roller coaster`,`activity`,`过山车,游乐园`],[`🎣`,`fishing pole and fish`,`activity`,`钓鱼`],[`🎤`,`microphone`,`activity`,`麦克风,唱歌,K歌`],[`🎥`,`movie camera`,`activity`,`摄影机,电影,拍摄`],[`🎦`,`cinema`,`activity`,``],[`🎧`,`headphone`,`activity`,`耳机,听歌,音乐,戴`],[`🎨`,`artist palette`,`activity`,`调色板,画画,美术,艺术`],[`🎩`,`top hat`,`activity`,`礼帽,魔术帽,帽子`],[`🎪`,`circus tent`,`activity`,`马戏团`],[`🎫`,`ticket`,`activity`,`门票,票,入场券`],[`🎬`,`clapper board`,`activity`,`场记板,电影,拍戏,导演`],[`🎭`,`performing arts`,`activity`,`面具,戏剧,表演,舞台`],[`🎮`,`video game`,`activity`,`游戏机,游戏,手柄,玩`],[`🎯`,`direct hit`,`activity`,`目标`],[`🎰`,`slot machine`,`activity`,``],[`🎱`,`billiards`,`activity`,`台球`],[`🎲`,`game die`,`activity`,`骰子,赌博,游戏`],[`🎳`,`bowling`,`activity`,`保龄球,球`],[`🎴`,`flower playing cards`,`activity`,`花牌,卡牌,纸牌`],[`🎵`,`musical note`,`activity`,`音符,音乐,歌`],[`🎶`,`multiple musical notes`,`activity`,`音符,音乐,唱歌`],[`🎷`,`saxophone`,`activity`,`萨克斯,爵士,乐器`],[`🎸`,`guitar`,`activity`,`吉他,弹吉他,摇滚`],[`🎹`,`musical keyboard`,`activity`,`钢琴,键盘,弹琴`],[`🎺`,`trumpet`,`activity`,`小号,喇叭,乐器`],[`🎻`,`violin`,`activity`,`小提琴,弦乐`],[`🎼`,`musical score`,`activity`,`乐谱,音乐,谱`],[`🎽`,`running shirt with sash`,`activity`,`背心`],[`🎾`,`tennis racquet and ball`,`activity`,`网球,球`],[`🎿`,`ski and ski boot`,`activity`,`滑雪`],[`🏀`,`basketball and hoop`,`activity`,`篮球,球`],[`🏁`,`chequered flag`,`flags`,`终点,旗帜,赛车,比赛`],[`🏂`,`snowboarder`,`activity`,``],[`🏃`,`runner`,`activity`,`跑步,跑,奔跑`],[`🏄`,`surfer`,`activity`,``],[`🏅`,`sports medal`,`activity`,`奖牌,奖章,荣誉`],[`🏆`,`trophy`,`activity`,``],[`🏇`,`horse racing`,`activity`,``],[`🏈`,`american football`,`activity`,`橄榄球,美式足球`],[`🏉`,`rugby football`,`activity`,`橄榄球,英式`],[`🏊`,`swimmer`,`activity`,``],[`🏋`,`weight lifter`,`activity`,``],[`🏌`,`golfer`,`activity`,``],[`🏍`,`racing motorcycle`,`activity`,``],[`🏎`,`racing car`,`activity`,``],[`🏏`,`cricket bat and ball`,`activity`,``],[`🏐`,`volleyball`,`activity`,`排球,球`],[`🏑`,`field hockey stick and ball`,`activity`,``],[`🏒`,`ice hockey stick and puck`,`activity`,``],[`🏓`,`table tennis paddle and ball`,`activity`,`乒乓球,乒乓,球`],[`🏔`,`snow capped mountain`,`activity`,``],[`🏕`,`camping`,`activity`,``],[`🏖`,`beach with umbrella`,`activity`,``],[`🏗`,`building construction`,`activity`,``],[`🏘`,`house buildings`,`activity`,``],[`🏙`,`cityscape`,`activity`,``],[`🏚`,`derelict house building`,`activity`,``],[`🏛`,`classical building`,`activity`,``],[`🏜`,`desert`,`activity`,``],[`🏝`,`desert island`,`activity`,``],[`🏞`,`national park`,`activity`,``],[`🏟`,`stadium`,`activity`,``],[`🏠`,`house building`,`travel`,`房子,家,住宅`],[`🏡`,`house with garden`,`travel`,`房子,家,花园`],[`🏢`,`office building`,`travel`,`办公楼,大楼,写字楼`],[`🏣`,`japanese post office`,`travel`,`邮局,邮政`],[`🏤`,`european post office`,`travel`,`邮局`],[`🏥`,`hospital`,`travel`,`医院,医疗`],[`🏦`,`bank`,`travel`,`银行,金融`],[`🏧`,`automated teller machine`,`travel`,``],[`🏨`,`hotel`,`travel`,`酒店,旅馆`],[`🏩`,`love hotel`,`travel`,`爱情旅馆,酒店`],[`🏪`,`convenience store`,`travel`,`便利店,商店`],[`🏫`,`school`,`travel`,`学校,校园`],[`🏬`,`department store`,`travel`,`商场,百货,购物`],[`🏭`,`factory`,`travel`,`工厂,工业`],[`🏮`,`izakaya lantern`,`travel`,``],[`🏯`,`japanese castle`,`objects`,`城堡,日本城堡`],[`🏰`,`european castle`,`travel`,`城堡,童话`],[`🏳`,`waving white flag`,`flags`,``],[`🏴`,`waving black flag`,`flags`,`黑旗`],[`🏵`,`rosette`,`objects`,``],[`🏷`,`label`,`objects`,``],[`🏸`,`badminton racquet and shuttlecock`,`activity`,`羽毛球,球`],[`🏹`,`bow and arrow`,`activity`,`射箭,弓箭,弓`],[`🏺`,`amphora`,`activity`,`陶罐,花瓶,双耳瓶`],[`🏻`,`emoji modifier fitzpatrick type-1-2`,`symbols`,``],[`🏼`,`emoji modifier fitzpatrick type-3`,`symbols`,``],[`🏽`,`emoji modifier fitzpatrick type-4`,`symbols`,``],[`🏾`,`emoji modifier fitzpatrick type-5`,`symbols`,``],[`🏿`,`emoji modifier fitzpatrick type-6`,`symbols`,``],[`🐀`,`rat`,`animals`,`老鼠,鼠`],[`🐁`,`mouse`,`animals`,`老鼠,鼠`],[`🐂`,`ox`,`animals`,`公牛,牛`],[`🐃`,`water buffalo`,`animals`,`水牛,牛`],[`🐄`,`cow`,`animals`,`奶牛,牛`],[`🐅`,`tiger`,`animals`,``],[`🐆`,`leopard`,`animals`,``],[`🐇`,`rabbit`,`animals`,`兔子,兔`],[`🐈`,`cat`,`animals`,`猫,猫咪`],[`🐉`,`dragon`,`animals`,`龙,中国龙`],[`🐊`,`crocodile`,`animals`,`鳄鱼,短吻鳄`],[`🐋`,`whale`,`animals`,`鲸鱼`],[`🐌`,`snail`,`animals`,``],[`🐍`,`snake`,`animals`,`蛇,爬行动物`],[`🐎`,`horse`,`animals`,``],[`🐏`,`ram`,`animals`,`羊,公羊`],[`🐐`,`goat`,`animals`,`山羊,羊`],[`🐑`,`sheep`,`animals`,`羊,绵羊`],[`🐒`,`monkey`,`animals`,``],[`🐓`,`rooster`,`animals`,`公鸡,鸡`],[`🐔`,`chicken`,`animals`,`鸡,母鸡`],[`🐕`,`dog`,`animals`,`狗,小狗`],[`🐖`,`pig`,`animals`,`猪`],[`🐗`,`boar`,`animals`,`野猪,猪`],[`🐘`,`elephant`,`animals`,`大象`],[`🐙`,`octopus`,`animals`,`章鱼,八爪鱼`],[`🐚`,`spiral shell`,`animals`,``],[`🐛`,`bug`,`animals`,``],[`🐜`,`ant`,`animals`,``],[`🐝`,`honeybee`,`animals`,``],[`🐞`,`lady beetle`,`animals`,``],[`🐟`,`fish`,`animals`,`鱼,鱼`],[`🐠`,`tropical fish`,`animals`,`热带鱼,鱼`],[`🐡`,`blowfish`,`animals`,`河豚,鱼`],[`🐢`,`turtle`,`animals`,`乌龟,慢`],[`🐣`,`hatching chick`,`animals`,`小鸡,破壳,孵化`],[`🐤`,`baby chick`,`animals`,`小鸡,黄,可爱`],[`🐥`,`front-facing baby chick`,`animals`,`小鸡,正面`],[`🐦`,`bird`,`animals`,`鸟`],[`🐧`,`penguin`,`animals`,`企鹅,南极`],[`🐨`,`koala`,`animals`,`考拉,无尾熊`],[`🐩`,`poodle`,`animals`,`贵宾犬,狗`],[`🐪`,`dromedary camel`,`animals`,`骆驼`],[`🐫`,`bactrian camel`,`animals`,`骆驼,双峰`],[`🐬`,`dolphin`,`animals`,`海豚,海洋`],[`🐭`,`mouse face`,`animals`,`老鼠,鼠`],[`🐮`,`cow face`,`animals`,`牛,奶牛`],[`🐯`,`tiger face`,`animals`,``],[`🐰`,`rabbit face`,`animals`,`兔子,兔,可爱`],[`🐱`,`cat face`,`animals`,``],[`🐲`,`dragon face`,`animals`,`龙,龙头`],[`🐳`,`spouting whale`,`animals`,`鲸鱼,喷水`],[`🐴`,`horse face`,`animals`,`马`],[`🐵`,`monkey face`,`animals`,``],[`🐶`,`dog face`,`animals`,``],[`🐷`,`pig face`,`animals`,`猪,猪头`],[`🐸`,`frog face`,`animals`,`青蛙,蛙`],[`🐹`,`hamster face`,`animals`,`仓鼠`],[`🐺`,`wolf face`,`animals`,``],[`🐻`,`bear face`,`animals`,`熊,泰迪熊`],[`🐼`,`panda face`,`animals`,``],[`🐽`,`pig nose`,`animals`,`猪鼻子,猪`],[`🐾`,`paw prints`,`animals`,`爪印,脚印`],[`🐿`,`chipmunk`,`animals`,``],[`👀`,`eyes`,`people`,``],[`👁`,`eye`,`people`,``],[`👂`,`ear`,`people`,`耳朵,听`],[`👃`,`nose`,`people`,`鼻子,闻`],[`👄`,`mouth`,`people`,`嘴巴,嘴唇,吻`],[`👅`,`tongue`,`people`,`舌头,舔`],[`👆`,`white up pointing backhand index`,`people`,`指,上面,向上`],[`👇`,`white down pointing backhand index`,`people`,`指,下面,向下`],[`👈`,`white left pointing backhand index`,`people`,`指,左边,指向`],[`👉`,`white right pointing backhand index`,`people`,`指,右边,指向`],[`👊`,`fisted hand sign`,`people`,`拳头,打,战斗`],[`👋`,`waving hand sign`,`people`,`挥手,再见,你好`],[`👌`,`ok hand sign`,`people`,`OK,好,可以`],[`👍`,`thumbs up sign`,`people`,`点赞,好,赞,棒`],[`👎`,`thumbs down sign`,`people`,`差评,不好,踩`],[`👏`,`clapping hands sign`,`people`,`鼓掌,拍手,掌声`],[`👐`,`open hands sign`,`people`,`张开,手,开放`],[`👑`,`crown`,`people`,`皇冠,王冠,国王,女王`],[`👒`,`womans hat`,`people`,`帽子,草帽,遮阳帽`],[`👓`,`eyeglasses`,`people`,`眼镜`],[`👔`,`necktie`,`people`,`领带,西装,工作`],[`👕`,`t-shirt`,`people`,`衣服,T恤`],[`👖`,`jeans`,`people`,`裤子,牛仔裤`],[`👗`,`dress`,`people`,`裙子,连衣裙`],[`👘`,`kimono`,`people`,`和服`],[`👙`,`bikini`,`people`,`比基尼,泳装`],[`👚`,`womans clothes`,`people`,`女装,衣服`],[`👛`,`purse`,`people`,`钱包,小包`],[`👜`,`handbag`,`people`,`手提包,包包`],[`👝`,`pouch`,`people`,`手拿包,包包`],[`👞`,`mans shoe`,`people`,`皮鞋,鞋`],[`👟`,`athletic shoe`,`people`,`运动鞋,跑鞋`],[`👠`,`high-heeled shoe`,`people`,`高跟鞋,鞋`],[`👡`,`womans sandal`,`people`,`凉鞋,鞋`],[`👢`,`womans boots`,`people`,`靴子,长靴`],[`👣`,`footprints`,`people`,`脚印,脚步,足迹`],[`👤`,`bust in silhouette`,`people`,`人,剪影,用户`],[`👥`,`busts in silhouette`,`people`,`人群,人,多个人`],[`👦`,`boy`,`people`,`男孩,小男孩`],[`👧`,`girl`,`people`,`女孩,小女孩`],[`👨`,`man`,`people`,`男人,男士`],[`👩`,`woman`,`people`,`女人,女士`],[`👪`,`family`,`people`,`家庭`],[`👫`,`woman and man holding hands`,`people`,``],[`👬`,`men holding hands`,`people`,``],[`👭`,`women holding hands`,`people`,``],[`👮`,`police officer`,`people`,`警察,警官`],[`👯`,`woman with bunny ears`,`people`,`兔子舞,蹦迪,派对`],[`👰`,`bride with veil`,`people`,`新娘,婚纱,结婚`],[`👱`,`person with blond hair`,`people`,``],[`👲`,`man with gua pi mao`,`people`,`中国人`],[`👳`,`man with turban`,`people`,`包头巾,印度,阿拉伯`],[`👴`,`older man`,`people`,`老人,老爷爷`],[`👵`,`older woman`,`people`,`老人,老奶奶`],[`👶`,`baby`,`people`,`婴儿,宝宝,小孩`],[`👷`,`construction worker`,`people`,`工人`],[`👸`,`princess`,`people`,`公主,女王`],[`👹`,`japanese ogre`,`people`,`妖怪,鬼,怪物`],[`👺`,`japanese goblin`,`people`,`天狗,怪物,鬼`],[`👻`,`ghost`,`people`,`幽灵,鬼,万圣节`],[`👼`,`baby angel`,`people`,`天使,婴儿,可爱`],[`👽`,`extraterrestrial alien`,`people`,`外星人,ET,飞碟`],[`👾`,`alien monster`,`people`,`外星人,怪兽,游戏`],[`👿`,`imp`,`people`,`恶魔,愤怒`],[`💀`,`skull`,`people`,`骷髅,死亡,骨头`],[`💁`,`information desk person`,`people`,``],[`💂`,`guardsman`,`people`,`卫兵,士兵`],[`💃`,`dancer`,`people`,`跳舞,舞女,跳舞`],[`💄`,`lipstick`,`people`,`口红,化妆`],[`💅`,`nail polish`,`people`,`美甲,指甲,涂`],[`💆`,`face massage`,`people`,`按摩,放松,头部`],[`💇`,`haircut`,`people`,`理发,剪发,发型`],[`💈`,`barber pole`,`people`,`理发店,理发`],[`💉`,`syringe`,`people`,`注射器,针,疫苗`],[`💊`,`pill`,`people`,`药丸,药,胶囊`],[`💋`,`kiss mark`,`people`,`吻,口红印,亲亲`],[`💌`,`love letter`,`people`,`情书,信,爱情`],[`💍`,`ring`,`people`,`戒指,钻戒,结婚`],[`💎`,`gem stone`,`people`,`钻石,宝石,珠宝`],[`💏`,`kiss`,`people`,``],[`💐`,`bouquet`,`smileys`,`花束,花,礼物`],[`💑`,`couple with heart`,`smileys`,``],[`💒`,`wedding`,`smileys`,`教堂,婚礼,教堂婚礼`],[`💓`,`beating heart`,`smileys`,`爱心,跳动,心跳`],[`💔`,`broken heart`,`smileys`,`心碎,伤心,破碎`],[`💕`,`two hearts`,`smileys`,`爱心,两个,喜欢`],[`💖`,`sparkling heart`,`smileys`,`爱心,闪光,喜欢`],[`💗`,`growing heart`,`smileys`,`爱心,跳动,喜欢`],[`💘`,`heart with arrow`,`smileys`,`爱心,箭,丘比特`],[`💙`,`blue heart`,`smileys`,``],[`💚`,`green heart`,`smileys`,``],[`💛`,`yellow heart`,`smileys`,``],[`💜`,`purple heart`,`smileys`,``],[`💝`,`heart with ribbon`,`smileys`,`爱心,礼物,蝴蝶结`],[`💞`,`revolving hearts`,`smileys`,`爱心,旋转,轮回`],[`💟`,`heart decoration`,`smileys`,`爱心,符号`],[`💠`,`diamond shape with a dot inside`,`objects`,``],[`💡`,`electric light bulb`,`objects`,``],[`💢`,`anger symbol`,`objects`,`生气,怒气`],[`💣`,`bomb`,`objects`,`炸弹,爆炸`],[`💤`,`sleeping symbol`,`objects`,`睡觉,打呼,困`],[`💥`,`collision symbol`,`objects`,``],[`💦`,`splashing sweat symbol`,`objects`,`汗,水,泪`],[`💧`,`droplet`,`objects`,`水滴,水,眼泪`],[`💨`,`dash symbol`,`objects`,`风,跑,快,烟雾`],[`💩`,`pile of poo`,`objects`,`大便,屎,狗屎`],[`💪`,`flexed biceps`,`people`,`肌肉,力量,加油,强壮`],[`💫`,`dizzy symbol`,`objects`,`星星,旋转`],[`💬`,`speech balloon`,`objects`,`对话,聊天`],[`💭`,`thought balloon`,`objects`,`想法,思考,气泡`],[`💮`,`white flower`,`objects`,``],[`💯`,`hundred points symbol`,`objects`,``],[`💰`,`money bag`,`objects`,`钱袋,钱,金钱`],[`💱`,`currency exchange`,`objects`,``],[`💲`,`heavy dollar sign`,`objects`,``],[`💳`,`credit card`,`objects`,`信用卡,银行卡,支付`],[`💴`,`banknote with yen sign`,`objects`,`日元,日圆,钱`],[`💵`,`banknote with dollar sign`,`objects`,`美元,美金,钱`],[`💶`,`banknote with euro sign`,`objects`,`欧元,钱`],[`💷`,`banknote with pound sign`,`objects`,`英镑,钱`],[`💸`,`money with wings`,`objects`,`钱,飞钱,花钱`],[`💹`,`chart with upwards trend and yen sign`,`objects`,`股票,上涨,图表,增长`],[`💺`,`seat`,`objects`,`座位,椅子,飞机座位`],[`💻`,`personal computer`,`objects`,`电脑,笔记本,笔记本电脑`],[`💼`,`briefcase`,`objects`,`公文包,工作,商务`],[`💽`,`minidisc`,`objects`,`光盘,磁盘`],[`💾`,`floppy disk`,`objects`,`软盘,保存`],[`💿`,`optical disc`,`objects`,`光盘,CD`],[`📀`,`dvd`,`objects`,`光盘,DVD`],[`📁`,`file folder`,`objects`,`文件夹`],[`📂`,`open file folder`,`objects`,`文件夹,打开`],[`📃`,`page with curl`,`objects`,`文件,文档`],[`📄`,`page facing up`,`objects`,`文件,文档,纸`],[`📅`,`calendar`,`objects`,`日历`],[`📆`,`tear-off calendar`,`objects`,`日历,日历页`],[`📇`,`card index`,`objects`,`名片,索引卡`],[`📈`,`chart with upwards trend`,`objects`,``],[`📉`,`chart with downwards trend`,`objects`,``],[`📊`,`bar chart`,`objects`,``],[`📋`,`clipboard`,`objects`,`剪贴板,清单,列表`],[`📌`,`pushpin`,`objects`,``],[`📍`,`round pushpin`,`objects`,``],[`📎`,`paperclip`,`objects`,``],[`📏`,`straight ruler`,`objects`,``],[`📐`,`triangular ruler`,`objects`,``],[`📑`,`bookmark tabs`,`objects`,`书签,标签,文件`],[`📒`,`ledger`,`objects`,``],[`📓`,`notebook`,`objects`,``],[`📔`,`notebook with decorative cover`,`objects`,``],[`📕`,`closed book`,`objects`,``],[`📖`,`open book`,`objects`,``],[`📗`,`green book`,`objects`,``],[`📘`,`blue book`,`objects`,``],[`📙`,`orange book`,`objects`,``],[`📚`,`books`,`objects`,``],[`📛`,`name badge`,`objects`,``],[`📜`,`scroll`,`objects`,``],[`📝`,`memo`,`objects`,`笔记,备忘录,写作,文档`],[`📞`,`telephone receiver`,`objects`,`电话`],[`📟`,`pager`,`objects`,`寻呼机,传呼机`],[`📠`,`fax machine`,`objects`,`传真机,传真`],[`📡`,`satellite antenna`,`objects`,`天线,卫星,信号`],[`📢`,`public address loudspeaker`,`objects`,``],[`📣`,`cheering megaphone`,`objects`,``],[`📤`,`outbox tray`,`objects`,`发送,输出,上传`],[`📥`,`inbox tray`,`objects`,`接收,下载,收件箱`],[`📦`,`package`,`objects`,`包裹,快递,箱子`],[`📧`,`e-mail symbol`,`objects`,`邮件,电子邮件`],[`📨`,`incoming envelope`,`objects`,`邮件,收到`],[`📩`,`envelope with downwards arrow above`,`objects`,`邮件,发送`],[`📪`,`closed mailbox with lowered flag`,`objects`,`邮箱,关闭`],[`📫`,`closed mailbox with raised flag`,`objects`,`邮箱,信箱,邮件`],[`📬`,`open mailbox with raised flag`,`objects`,`邮箱,有信`],[`📭`,`open mailbox with lowered flag`,`objects`,`邮箱,无信`],[`📮`,`postbox`,`objects`,`邮筒,邮政`],[`📯`,`postal horn`,`objects`,``],[`📰`,`newspaper`,`objects`,`报纸,新闻,报`],[`📱`,`mobile phone`,`objects`,`手机,智能手机,电话`],[`📲`,`mobile phone with rightwards arrow at left`,`objects`,`手机,接收,信号`],[`📳`,`vibration mode`,`objects`,``],[`📴`,`mobile phone off`,`objects`,``],[`📵`,`no mobile phones`,`objects`,``],[`📶`,`antenna with bars`,`objects`,``],[`📷`,`camera`,`objects`,`相机,拍照,照片`],[`📸`,`camera with flash`,`objects`,`相机,闪光灯,拍照`],[`📹`,`video camera`,`objects`,`摄像机,录像`],[`📺`,`television`,`objects`,``],[`📻`,`radio`,`objects`,`收音机,广播`],[`📼`,`videocassette`,`objects`,`录像带,磁带`],[`📽`,`film projector`,`objects`,``],[`📿`,`prayer beads`,`objects`,`念珠,佛珠,项链`],[`🔀`,`twisted rightwards arrows`,`objects`,``],[`🔁`,`clockwise rightwards and leftwards open circle arrows`,`objects`,``],[`🔂`,`clockwise rightwards and leftwards open circle arrows with circled one overlay`,`objects`,``],[`🔃`,`clockwise downwards and upwards open circle arrows`,`objects`,``],[`🔄`,`anticlockwise downwards and upwards open circle arrows`,`objects`,``],[`🔅`,`low brightness symbol`,`objects`,``],[`🔆`,`high brightness symbol`,`objects`,``],[`🔇`,`speaker with cancellation stroke`,`objects`,``],[`🔈`,`speaker`,`objects`,``],[`🔉`,`speaker with one sound wave`,`objects`,``],[`🔊`,`speaker with three sound waves`,`objects`,``],[`🔋`,`battery`,`objects`,``],[`🔌`,`electric plug`,`objects`,``],[`🔍`,`left-pointing magnifying glass`,`objects`,`搜索,放大镜,查找,查询`],[`🔎`,`right-pointing magnifying glass`,`objects`,`搜索,放大镜,查找`],[`🔏`,`lock with ink pen`,`objects`,`锁,保密,笔`],[`🔐`,`closed lock with key`,`objects`,`锁,安全,钥匙`],[`🔑`,`key`,`objects`,`钥匙,解锁`],[`🔒`,`lock`,`objects`,`锁,锁定,安全`],[`🔓`,`open lock`,`objects`,`解锁,打开`],[`🔔`,`bell`,`objects`,``],[`🔕`,`bell with cancellation stroke`,`objects`,``],[`🔖`,`bookmark`,`objects`,`书签,标记`],[`🔗`,`link symbol`,`objects`,``],[`🔘`,`radio button`,`objects`,``],[`🔙`,`back with leftwards arrow above`,`objects`,``],[`🔚`,`end with leftwards arrow above`,`objects`,``],[`🔛`,`on with exclamation mark with left right arrow above`,`objects`,``],[`🔜`,`soon with rightwards arrow above`,`objects`,``],[`🔝`,`top with upwards arrow above`,`objects`,``],[`🔞`,`no one under eighteen symbol`,`objects`,``],[`🔟`,`keycap 10`,`objects`,``],[`🔠`,`input symbol for latin capital letters`,`objects`,``],[`🔡`,`input symbol for latin small letters`,`objects`,``],[`🔢`,`input symbol for numbers`,`objects`,``],[`🔣`,`input symbol for symbols`,`objects`,``],[`🔤`,`input symbol for latin letters`,`objects`,``],[`🔥`,`fire`,`objects`,``],[`🔦`,`electric torch`,`objects`,``],[`🔧`,`wrench`,`objects`,`扳手,工具,维修`],[`🔨`,`hammer`,`objects`,`锤子,工具`],[`🔩`,`nut and bolt`,`objects`,`螺丝,螺母`],[`🔪`,`hocho`,`objects`,``],[`🔫`,`pistol`,`objects`,`枪`],[`🔬`,`microscope`,`objects`,`显微镜,科学,研究`],[`🔭`,`telescope`,`objects`,`望远镜,天文,观察`],[`🔮`,`crystal ball`,`objects`,``],[`🔯`,`six pointed star with middle dot`,`objects`,``],[`🔰`,`japanese symbol for beginner`,`objects`,``],[`🔱`,`trident emblem`,`objects`,``],[`🔲`,`black square button`,`objects`,``],[`🔳`,`white square button`,`objects`,``],[`🔴`,`large red circle`,`objects`,``],[`🔵`,`large blue circle`,`objects`,``],[`🔶`,`large orange diamond`,`objects`,``],[`🔷`,`large blue diamond`,`objects`,``],[`🔸`,`small orange diamond`,`objects`,``],[`🔹`,`small blue diamond`,`objects`,``],[`🔺`,`up-pointing red triangle`,`objects`,``],[`🔻`,`down-pointing red triangle`,`objects`,``],[`🔼`,`up-pointing small red triangle`,`objects`,``],[`🔽`,`down-pointing small red triangle`,`objects`,``],[`🕉`,`om symbol`,`objects`,``],[`🕊`,`dove of peace`,`objects`,``],[`🕋`,`kaaba`,`objects`,`天房,麦加,伊斯兰`],[`🕌`,`mosque`,`objects`,`清真寺,伊斯兰`],[`🕍`,`synagogue`,`objects`,`犹太教堂,犹太`],[`🕎`,`menorah with nine branches`,`objects`,``],[`🕐`,`clock face one oclock`,`objects`,`一点,时钟`],[`🕑`,`clock face two oclock`,`objects`,`两点,时钟`],[`🕒`,`clock face three oclock`,`objects`,`三点,时钟`],[`🕓`,`clock face four oclock`,`objects`,`四点,时钟`],[`🕔`,`clock face five oclock`,`objects`,`五点,时钟`],[`🕕`,`clock face six oclock`,`objects`,`六点,时钟`],[`🕖`,`clock face seven oclock`,`objects`,`七点,时钟`],[`🕗`,`clock face eight oclock`,`objects`,`八点,时钟`],[`🕘`,`clock face nine oclock`,`objects`,`九点,时钟`],[`🕙`,`clock face ten oclock`,`objects`,`十点,时钟`],[`🕚`,`clock face eleven oclock`,`objects`,`十一点,时钟`],[`🕛`,`clock face twelve oclock`,`objects`,`十二点,时钟,时间`],[`🕜`,`clock face one-thirty`,`objects`,``],[`🕝`,`clock face two-thirty`,`objects`,``],[`🕞`,`clock face three-thirty`,`objects`,``],[`🕟`,`clock face four-thirty`,`objects`,``],[`🕠`,`clock face five-thirty`,`objects`,``],[`🕡`,`clock face six-thirty`,`objects`,``],[`🕢`,`clock face seven-thirty`,`objects`,``],[`🕣`,`clock face eight-thirty`,`objects`,``],[`🕤`,`clock face nine-thirty`,`objects`,``],[`🕥`,`clock face ten-thirty`,`objects`,``],[`🕦`,`clock face eleven-thirty`,`objects`,``],[`🕧`,`clock face twelve-thirty`,`objects`,``],[`🕯`,`candle`,`objects`,``],[`🕰`,`mantelpiece clock`,`objects`,``],[`🕳`,`hole`,`objects`,``],[`🕴`,`man in business suit levitating`,`objects`,``],[`🕵`,`sleuth or spy`,`objects`,``],[`🕶`,`dark sunglasses`,`objects`,``],[`🕷`,`spider`,`objects`,``],[`🕸`,`spider web`,`objects`,``],[`🕹`,`joystick`,`objects`,``],[`🕺`,`man dancing`,`objects`,`跳舞,舞男`],[`🖇`,`linked paperclips`,`objects`,``],[`🖊`,`lower left ballpoint pen`,`objects`,``],[`🖋`,`lower left fountain pen`,`objects`,``],[`🖌`,`lower left paintbrush`,`objects`,``],[`🖍`,`lower left crayon`,`objects`,``],[`🖐`,`raised hand with fingers splayed`,`objects`,``],[`🖕`,`reversed hand with middle finger extended`,`objects`,`中指,骂人`],[`🖖`,`raised hand with part between middle and ring fingers`,`objects`,`瓦肯,举手,胜利`],[`🖤`,`black heart`,`objects`,``],[`🖥`,`desktop computer`,`objects`,``],[`🖨`,`printer`,`objects`,``],[`🖱`,`three button mouse`,`objects`,``],[`🖲`,`trackball`,`objects`,``],[`🖼`,`frame with picture`,`objects`,``],[`🗂`,`card index dividers`,`objects`,``],[`🗃`,`card file box`,`objects`,``],[`🗄`,`file cabinet`,`objects`,``],[`🗑`,`wastebasket`,`objects`,``],[`🗒`,`spiral note pad`,`objects`,``],[`🗓`,`spiral calendar pad`,`objects`,``],[`🗜`,`compression`,`objects`,``],[`🗝`,`old key`,`objects`,``],[`🗞`,`rolled-up newspaper`,`objects`,``],[`🗡`,`dagger knife`,`objects`,``],[`🗣`,`speaking head in silhouette`,`objects`,``],[`🗨`,`left speech bubble`,`objects`,``],[`🗯`,`right anger bubble`,`objects`,``],[`🗳`,`ballot box with ballot`,`objects`,``],[`🗺`,`world map`,`objects`,``],[`🗻`,`mount fuji`,`objects`,`富士山,山`],[`🗼`,`tokyo tower`,`objects`,`塔,东京塔`],[`🗽`,`statue of liberty`,`objects`,`自由女神像,纽约`],[`🗾`,`silhouette of japan`,`objects`,``],[`🗿`,`moyai`,`objects`,`雕像`],[`😀`,`grinning face`,`smileys`,`笑脸,开心,高兴`],[`😁`,`grinning face with smiling eyes`,`smileys`,`笑脸,开心`],[`😂`,`face with tears of joy`,`smileys`,`笑哭,大笑,笑`],[`😃`,`smiling face with open mouth`,`smileys`,`笑脸,开心`],[`😄`,`smiling face with open mouth and smiling eyes`,`smileys`,`笑脸,开心`],[`😅`,`smiling face with open mouth and cold sweat`,`smileys`,`笑脸,汗,尴尬`],[`😆`,`smiling face with open mouth and tightly-closed eyes`,`smileys`,`笑脸,大笑`],[`😇`,`smiling face with halo`,`smileys`,`天使,微笑,善良`],[`😈`,`smiling face with horns`,`smileys`,`恶魔,坏笑,邪恶`],[`😉`,`winking face`,`smileys`,`眨眼,调皮`],[`😊`,`smiling face with smiling eyes`,`smileys`,`微笑,开心,脸红`],[`😋`,`face savouring delicious food`,`smileys`,`好吃,美味,舔`],[`😌`,`relieved face`,`smileys`,`放松,安心`],[`😍`,`smiling face with heart-shaped eyes`,`smileys`,`爱,喜欢,花痴`],[`😎`,`smiling face with sunglasses`,`smileys`,`酷,墨镜,帅气`],[`😏`,`smirking face`,`smileys`,`得意,微笑,坏笑`],[`😐`,`neutral face`,`smileys`,`无语,面无表情`],[`😑`,`expressionless face`,`smileys`,`无语,面无表情`],[`😒`,`unamused face`,`smileys`,`不满,无语,翻白眼`],[`😓`,`face with cold sweat`,`smileys`,`冷汗,尴尬`],[`😔`,`pensive face`,`smileys`,`难过,低落`],[`😕`,`confused face`,`smileys`,`困惑,不解`],[`😖`,`confounded face`,`smileys`,`纠结,痛苦`],[`😗`,`kissing face`,`smileys`,`亲亲,吻`],[`😘`,`face throwing a kiss`,`smileys`,`飞吻,亲亲,爱`],[`😙`,`kissing face with smiling eyes`,`smileys`,``],[`😚`,`kissing face with closed eyes`,`smileys`,`亲亲,吻`],[`😛`,`face with stuck-out tongue`,`smileys`,`吐舌头,调皮`],[`😜`,`face with stuck-out tongue and winking eye`,`smileys`,`吐舌头,调皮,眨眼`],[`😝`,`face with stuck-out tongue and tightly-closed eyes`,`smileys`,`吐舌头,调皮`],[`😞`,`disappointed face`,`smileys`,`失望,难过`],[`😟`,`worried face`,`smileys`,`担心,忧虑`],[`😠`,`angry face`,`smileys`,`生气,愤怒`],[`😡`,`pouting face`,`smileys`,`生气,愤怒,红脸`],[`😢`,`crying face`,`smileys`,`哭,伤心,流泪`],[`😣`,`persevering face`,`smileys`,`挣扎,痛苦`],[`😤`,`face with look of triumph`,`smileys`,`生气,冒烟,气`],[`😥`,`disappointed but relieved face`,`smileys`,`难过,失望,松气`],[`😦`,`frowning face with open mouth`,`smileys`,`惊讶,张嘴`],[`😧`,`anguished face`,`smileys`,`震惊,痛苦`],[`😨`,`fearful face`,`smileys`,`害怕,恐惧`],[`😩`,`weary face`,`smileys`,`累,疲惫,哭`],[`😪`,`sleepy face`,`smileys`,`困,想睡`],[`😫`,`tired face`,`smileys`,`累,疲惫`],[`😬`,`grimacing face`,`smileys`,`尴尬,咧嘴`],[`😭`,`loudly crying face`,`smileys`,`大哭,伤心,哭`],[`😮`,`face with open mouth`,`smileys`,`惊讶,哇`],[`😯`,`hushed face`,`smileys`,`惊讶,安静`],[`😰`,`face with open mouth and cold sweat`,`smileys`,`担心,冷汗`],[`😱`,`face screaming in fear`,`smileys`,`尖叫,害怕,恐怖`],[`😲`,`astonished face`,`smileys`,`震惊,惊讶`],[`😳`,`flushed face`,`smileys`,`脸红,害羞,震惊`],[`😴`,`sleeping face`,`smileys`,`睡觉,睡觉`],[`😵`,`dizzy face`,`smileys`,`晕,头晕,死`],[`😶`,`face without mouth`,`smileys`,`沉默,无语`],[`😷`,`face with medical mask`,`smileys`,`生病,口罩,感冒`],[`😸`,`grinning cat face with smiling eyes`,`smileys`,`猫,笑脸`],[`😹`,`cat face with tears of joy`,`smileys`,`猫,笑哭`],[`😺`,`smiling cat face with open mouth`,`smileys`,`猫,笑脸,开心`],[`😻`,`smiling cat face with heart-shaped eyes`,`smileys`,`猫,爱,喜欢`],[`😼`,`cat face with wry smile`,`smileys`,`猫,坏笑`],[`😽`,`kissing cat face with closed eyes`,`smileys`,`猫,亲亲`],[`😾`,`pouting cat face`,`smileys`,`猫,生气`],[`😿`,`crying cat face`,`smileys`,`猫,哭,伤心`],[`🙀`,`weary cat face`,`smileys`,`猫,震惊,害怕`],[`🙁`,`slightly frowning face`,`smileys`,`难过,失望`],[`🙂`,`slightly smiling face`,`smileys`,`微笑,笑`],[`🙃`,`upside-down face`,`smileys`,`微笑,倒`],[`🙄`,`face with rolling eyes`,`smileys`,`翻白眼,无语`],[`🙅`,`face with no good gesture`,`smileys`,``],[`🙆`,`face with ok gesture`,`smileys`,``],[`🙇`,`person bowing deeply`,`smileys`,``],[`🙈`,`see-no-evil monkey`,`smileys`,``],[`🙉`,`hear-no-evil monkey`,`smileys`,``],[`🙊`,`speak-no-evil monkey`,`smileys`,``],[`🙋`,`happy person raising one hand`,`smileys`,``],[`🙌`,`person raising both hands in celebration`,`smileys`,`欢呼,举起,庆祝`],[`🙍`,`person frowning`,`smileys`,``],[`🙎`,`person with pouting face`,`smileys`,``],[`🙏`,`person with folded hands`,`smileys`,`祈祷,拜托,感谢,合十`],[`🚀`,`rocket`,`travel`,`火箭,发射,太空`],[`🚁`,`helicopter`,`travel`,`直升机`],[`🚂`,`steam locomotive`,`travel`,`火车,蒸汽火车`],[`🚃`,`railway car`,`travel`,`电车,火车`],[`🚄`,`high-speed train`,`travel`,`高铁,动车,火车`],[`🚅`,`high-speed train with bullet nose`,`travel`,``],[`🚆`,`train`,`travel`,`火车,铁路`],[`🚇`,`metro`,`travel`,`地铁,地铁站`],[`🚈`,`light rail`,`travel`,`轻轨,轨道交通`],[`🚉`,`station`,`travel`,`火车站,车站`],[`🚊`,`tram`,`travel`,`电车`],[`🚋`,`tram car`,`travel`,`电车,有轨电车`],[`🚌`,`bus`,`travel`,`公交车,巴士`],[`🚍`,`oncoming bus`,`travel`,`公交车`],[`🚎`,`trolleybus`,`travel`,`无轨电车,巴士`],[`🚏`,`bus stop`,`travel`,`公交站,车站`],[`🚐`,`minibus`,`travel`,`面包车,小巴`],[`🚑`,`ambulance`,`travel`,`救护车,急救`],[`🚒`,`fire engine`,`travel`,`消防车,救火`],[`🚓`,`police car`,`travel`,`警车,警察`],[`🚔`,`oncoming police car`,`travel`,`警车,巡逻`],[`🚕`,`taxi`,`travel`,`出租车,的士`],[`🚖`,`oncoming taxi`,`travel`,`出租车`],[`🚗`,`automobile`,`travel`,`汽车,轿车,车`],[`🚘`,`oncoming automobile`,`travel`,`汽车`],[`🚙`,`recreational vehicle`,`travel`,`SUV,越野车,汽车`],[`🚚`,`delivery truck`,`travel`,`卡车,货车`],[`🚛`,`articulated lorry`,`travel`,`卡车,货车`],[`🚜`,`tractor`,`travel`,`拖拉机,农用`],[`🚝`,`monorail`,`travel`,`单轨,单轨列车`],[`🚞`,`mountain railway`,`travel`,`火车,山区铁路`],[`🚟`,`suspension railway`,`travel`,`缆车,悬挂列车`],[`🚠`,`mountain cableway`,`travel`,`缆车,高山`],[`🚡`,`aerial tramway`,`travel`,`缆车,索道`],[`🚢`,`ship`,`travel`,`轮船,船,大海`],[`🚣`,`rowboat`,`travel`,``],[`🚤`,`speedboat`,`travel`,`快艇,汽艇`],[`🚥`,`horizontal traffic light`,`travel`,`红绿灯,交通信号灯`],[`🚦`,`vertical traffic light`,`travel`,`红绿灯,信号灯`],[`🚧`,`construction sign`,`travel`,`施工,施工中,路障`],[`🚨`,`police cars revolving light`,`travel`,`警车灯,警报,紧急`],[`🚩`,`triangular flag on post`,`travel`,`红旗,旗帜,标志`],[`🚪`,`door`,`travel`,`门,房门`],[`🚫`,`no entry sign`,`travel`,``],[`🚬`,`smoking symbol`,`travel`,`香烟,烟,吸烟`],[`🚭`,`no smoking symbol`,`travel`,``],[`🚮`,`put litter in its place symbol`,`travel`,`垃圾,清理`],[`🚯`,`do not litter symbol`,`travel`,``],[`🚰`,`potable water symbol`,`travel`,``],[`🚱`,`non-potable water symbol`,`travel`,``],[`🚲`,`bicycle`,`travel`,`自行车,单车,骑行`],[`🚳`,`no bicycles`,`travel`,``],[`🚴`,`bicyclist`,`travel`,``],[`🚵`,`mountain bicyclist`,`travel`,``],[`🚶`,`pedestrian`,`travel`,`走路,步行,散步`],[`🚷`,`no pedestrians`,`travel`,``],[`🚸`,`children crossing`,`travel`,``],[`🚹`,`mens symbol`,`travel`,``],[`🚺`,`womens symbol`,`travel`,``],[`🚻`,`restroom`,`travel`,``],[`🚼`,`baby symbol`,`travel`,``],[`🚽`,`toilet`,`travel`,`马桶,厕所,卫生间`],[`🚾`,`water closet`,`travel`,``],[`🚿`,`shower`,`travel`,`淋浴,洗澡`],[`🛀`,`bath`,`travel`,`泡澡`],[`🛁`,`bathtub`,`travel`,`浴缸,洗澡,泡澡`],[`🛂`,`passport control`,`travel`,``],[`🛃`,`customs`,`travel`,``],[`🛄`,`baggage claim`,`travel`,``],[`🛅`,`left luggage`,`travel`,``],[`🛋`,`couch and lamp`,`travel`,``],[`🛌`,`sleeping accommodation`,`travel`,`睡觉`],[`🛍`,`shopping bags`,`travel`,``],[`🛎`,`bellhop bell`,`travel`,``],[`🛏`,`bed`,`travel`,``],[`🛐`,`place of worship`,`travel`,``],[`🛑`,`octagonal sign`,`travel`,`停止,停车,红圈`],[`🛒`,`shopping trolley`,`travel`,`购物车,购物`],[`🛕`,`hindu temple`,`travel`,`印度教神庙`],[`🛖`,`hut`,`travel`,`草屋,小屋`],[`🛗`,`elevator`,`travel`,``],[`🛜`,`wireless`,`travel`,``],[`🛝`,`playground slide`,`travel`,``],[`🛞`,`wheel`,`travel`,`车轮,轮胎`],[`🛟`,`ring buoy`,`travel`,`救生圈,救生`],[`🛠`,`hammer and wrench`,`travel`,``],[`🛡`,`shield`,`travel`,``],[`🛢`,`oil drum`,`travel`,``],[`🛣`,`motorway`,`travel`,``],[`🛤`,`railway track`,`travel`,``],[`🛥`,`motor boat`,`travel`,``],[`🛩`,`small airplane`,`travel`,``],[`🛫`,`airplane departure`,`travel`,`起飞,飞机,出发`],[`🛬`,`airplane arriving`,`travel`,`降落,飞机,到达`],[`🛰`,`satellite`,`travel`,``],[`🛳`,`passenger ship`,`travel`,``],[`🛴`,`scooter`,`travel`,`滑板车,平衡车`],[`🛵`,`motor scooter`,`travel`,`摩托车,电动车,踏板车`],[`🛶`,`canoe`,`travel`,`独木舟,皮划艇`],[`🛷`,`sled`,`travel`,`雪橇,雪车`],[`🛸`,`flying saucer`,`travel`,`飞碟,UFO,外星人`],[`🛹`,`skateboard`,`travel`,`滑板`],[`🛺`,`auto rickshaw`,`travel`,`三轮车,突突车`],[`🛻`,`pickup truck`,`travel`,`皮卡,卡车`],[`🛼`,`roller skate`,`travel`,`轮滑`],[`🟠`,`large orange circle`,`symbols`,``],[`🟡`,`large yellow circle`,`symbols`,``],[`🟢`,`large green circle`,`symbols`,``],[`🟣`,`large purple circle`,`symbols`,``],[`🟤`,`large brown circle`,`symbols`,``],[`🟥`,`large red square`,`symbols`,``],[`🟦`,`large blue square`,`symbols`,``],[`🟧`,`large orange square`,`symbols`,``],[`🟨`,`large yellow square`,`symbols`,``],[`🟩`,`large green square`,`symbols`,``],[`🟪`,`large purple square`,`symbols`,``],[`🟫`,`large brown square`,`symbols`,``],[`🟰`,`heavy equals sign`,`symbols`,``],[`🤌`,`pinched fingers`,`symbols`,`手指,捏,意大利`],[`🤍`,`white heart`,`symbols`,`白心,白色,爱心`],[`🤎`,`brown heart`,`symbols`,`棕心,棕色,爱心`],[`🤏`,`pinching hand`,`symbols`,`捏,一点点,微小`],[`🤐`,`zipper-mouth face`,`smileys`,`闭嘴,不说`],[`🤑`,`money-mouth face`,`smileys`,`发财,金钱,贪婪`],[`🤒`,`face with thermometer`,`smileys`,`发烧,生病,温度计`],[`🤓`,`nerd face`,`smileys`,`书呆子,眼镜`],[`🤔`,`thinking face`,`smileys`,`思考,疑问,想`],[`🤕`,`face with head-bandage`,`smileys`,`受伤,包扎,头`],[`🤖`,`robot face`,`smileys`,`机器人,AI,机械`],[`🤗`,`hugging face`,`smileys`,`拥抱,欢迎`],[`🤘`,`sign of the horns`,`smileys`,`摇滚,手势,牛`],[`🤙`,`call me hand`,`smileys`,`打电话,挂,酷`],[`🤚`,`raised back of hand`,`smileys`,`手,举手,停`],[`🤛`,`left-facing fist`,`smileys`,`拳头,左边`],[`🤜`,`right-facing fist`,`smileys`,`拳头,右边`],[`🤝`,`handshake`,`smileys`,`握手,合作,协议`],[`🤞`,`hand with index and middle fingers crossed`,`smileys`,`祈祷,好运,手指交叉`],[`🤟`,`i love you hand sign`,`smileys`,`爱你,摇滚`],[`🤠`,`face with cowboy hat`,`smileys`,`牛仔,帽子`],[`🤡`,`clown face`,`smileys`,`小丑,马戏团`],[`🤢`,`nauseated face`,`smileys`,`恶心,呕吐`],[`🤣`,`rolling on the floor laughing`,`smileys`,`笑哭,大笑,笑`],[`🤤`,`drooling face`,`smileys`,`流口水,馋`],[`🤥`,`lying face`,`smileys`,`说谎,撒谎`],[`🤦`,`face palm`,`smileys`,`捂脸,无奈,扶额`],[`🤧`,`sneezing face`,`smileys`,`打喷嚏,感冒`],[`🤨`,`face with one eyebrow raised`,`symbols`,`怀疑,挑眉`],[`🤩`,`grinning face with star eyes`,`symbols`,`星星眼,兴奋,惊讶`],[`🤪`,`grinning face with one large and one small eye`,`symbols`,`疯狂,搞怪`],[`🤫`,`face with finger covering closed lips`,`symbols`,`嘘,安静`],[`🤬`,`serious face with symbols covering mouth`,`symbols`,`骂人,脏话,生气`],[`🤭`,`smiling face with smiling eyes and hand covering mouth`,`symbols`,`捂嘴,偷笑,惊讶`],[`🤮`,`face with open mouth vomiting`,`symbols`,`呕吐,恶心`],[`🤯`,`shocked face with exploding head`,`smileys`,`爆炸,震惊,头炸`],[`🤰`,`pregnant woman`,`people`,`孕妇,怀孕`],[`🤱`,`breast-feeding`,`people`,``],[`🤲`,`palms up together`,`people`,``],[`🤳`,`selfie`,`people`,`自拍,拍照`],[`🤴`,`prince`,`people`,`王子,国王`],[`🤵`,`man in tuxedo`,`people`,`新郎,西装,燕尾服`],[`🤶`,`mother christmas`,`people`,`圣诞奶奶,圣诞老人`],[`🤷`,`shrug`,`people`,`耸肩,无奈,不知道`],[`🤸`,`person doing cartwheel`,`people`,`翻跟头,体操,空翻`],[`🤹`,`juggling`,`people`,`杂耍`],[`🤺`,`fencer`,`people`,`击剑,剑术`],[`🤼`,`wrestlers`,`activity`,`摔跤,格斗`],[`🤽`,`water polo`,`activity`,``],[`🤾`,`handball`,`activity`,``],[`🤿`,`diving mask`,`activity`,`潜水面罩,潜水`],[`🥀`,`wilted flower`,`symbols`,``],[`🥁`,`drum with drumsticks`,`symbols`,`鼓,打鼓,乐器`],[`🥂`,`clinking glasses`,`symbols`,`干杯,香槟杯`],[`🥃`,`tumbler glass`,`symbols`,`威士忌,酒杯`],[`🥄`,`spoon`,`symbols`,`勺子,汤匙`],[`🥅`,`goal net`,`symbols`,`球门,网,进球`],[`🥇`,`first place medal`,`symbols`,`金牌,冠军,第一名,奖牌`],[`🥈`,`second place medal`,`symbols`,`银牌,第二名,奖牌`],[`🥉`,`third place medal`,`symbols`,`铜牌,第三名,奖牌`],[`🥊`,`boxing glove`,`symbols`,`拳击,拳击手套,打拳`],[`🥋`,`martial arts uniform`,`symbols`,`道服,武术,空手道`],[`🥌`,`curling stone`,`symbols`,`冰壶,冰壶`],[`🥍`,`lacrosse stick and ball`,`symbols`,``],[`🥎`,`softball`,`symbols`,`垒球,球`],[`🥏`,`flying disc`,`symbols`,`飞盘,飞碟`],[`🥐`,`croissant`,`food`,`牛角包,可颂`],[`🥑`,`avocado`,`food`,`牛油果,鳄梨`],[`🥒`,`cucumber`,`food`,`黄瓜`],[`🥓`,`bacon`,`food`,`培根,腊肉`],[`🥔`,`potato`,`food`,`土豆,马铃薯`],[`🥕`,`carrot`,`food`,`胡萝卜`],[`🥖`,`baguette bread`,`food`,`法棍,面包`],[`🥗`,`green salad`,`food`,`沙拉,蔬菜`],[`🥘`,`shallow pan of food`,`food`,`炖锅,海鲜饭`],[`🥙`,`stuffed flatbread`,`food`,`卷饼,肉夹馍`],[`🥚`,`egg`,`food`,`鸡蛋,蛋`],[`🥛`,`glass of milk`,`food`,`牛奶,奶`],[`🥜`,`peanuts`,`food`,``],[`🥝`,`kiwifruit`,`food`,`猕猴桃,奇异果`],[`🥞`,`pancakes`,`food`,`松饼,煎饼`],[`🥟`,`dumpling`,`food`,`饺子,锅贴`],[`🥠`,`fortune cookie`,`food`,`幸运饼干`],[`🥡`,`takeout box`,`food`,``],[`🥢`,`chopsticks`,`food`,`筷子`],[`🥣`,`bowl with spoon`,`food`,``],[`🥤`,`cup with straw`,`food`,`饮料,杯`],[`🥥`,`coconut`,`food`,`椰子`],[`🥦`,`broccoli`,`food`,`西兰花`],[`🥧`,`pie`,`food`,`派,馅饼`],[`🥨`,`pretzel`,`food`,`椒盐卷饼`],[`🥩`,`cut of meat`,`food`,`牛排,肉`],[`🥪`,`sandwich`,`food`,`三明治`],[`🥫`,`canned food`,`food`,`罐头,罐装`],[`🥬`,`leafy green`,`symbols`,`青菜,白菜,生菜`],[`🥭`,`mango`,`symbols`,`芒果`],[`🥮`,`moon cake`,`symbols`,``],[`🥯`,`bagel`,`symbols`,`贝果,面包圈`],[`🥰`,`smiling face with smiling eyes and three hearts`,`smileys`,`爱,微笑,爱心`],[`🥱`,`yawning face`,`smileys`,`打哈欠,困,无聊`],[`🥲`,`smiling face with tear`,`smileys`,``],[`🥳`,`face with party horn and party hat`,`smileys`,`庆祝,派对,欢呼`],[`🥴`,`face with uneven eyes and wavy mouth`,`smileys`,`晕,醉,头昏`],[`🥵`,`overheated face`,`smileys`,`热`],[`🥶`,`freezing face`,`smileys`,`冷`],[`🥷`,`ninja`,`people`,`忍者,忍者`],[`🥸`,`disguised face`,`symbols`,`伪装`],[`🥹`,`face holding back tears`,`symbols`,`感动,忍住,哭,泪目`],[`🥺`,`face with pleading eyes`,`smileys`,`可怜,委屈,求`],[`🥻`,`sari`,`symbols`,`纱丽,印度`],[`🥼`,`lab coat`,`symbols`,``],[`🥽`,`goggles`,`symbols`,``],[`🥾`,`hiking boot`,`symbols`,`靴子,登山鞋`],[`🥿`,`flat shoe`,`symbols`,`平底鞋,鞋`],[`🦀`,`crab`,`animals`,`螃蟹,海鲜`],[`🦁`,`lion face`,`animals`,``],[`🦂`,`scorpion`,`animals`,``],[`🦃`,`turkey`,`animals`,`火鸡,感恩节`],[`🦄`,`unicorn face`,`animals`,`独角兽,梦幻`],[`🦅`,`eagle`,`animals`,`老鹰,鹰`],[`🦆`,`duck`,`animals`,`鸭子,鸭`],[`🦇`,`bat`,`animals`,`蝙蝠`],[`🦈`,`shark`,`animals`,`鲨鱼,鱼`],[`🦉`,`owl`,`animals`,`猫头鹰,智慧`],[`🦊`,`fox face`,`animals`,``],[`🦋`,`butterfly`,`animals`,``],[`🦌`,`deer`,`animals`,`鹿,麋鹿`],[`🦍`,`gorilla`,`animals`,``],[`🦎`,`lizard`,`animals`,`蜥蜴,爬行动物`],[`🦏`,`rhinoceros`,`animals`,`犀牛`],[`🦐`,`shrimp`,`animals`,`虾,海鲜`],[`🦑`,`squid`,`animals`,`鱿鱼,海鲜`],[`🦒`,`giraffe face`,`animals`,`长颈鹿`],[`🦓`,`zebra face`,`animals`,`斑马`],[`🦔`,`hedgehog`,`animals`,`刺猬`],[`🦕`,`sauropod`,`animals`,`恐龙,雷龙`],[`🦖`,`t-rex`,`animals`,`恐龙,霸王龙`],[`🦗`,`cricket`,`animals`,``],[`🦘`,`kangaroo`,`animals`,`袋鼠`],[`🦙`,`llama`,`animals`,`羊驼,草泥马`],[`🦚`,`peacock`,`animals`,`孔雀,开屏`],[`🦛`,`hippopotamus`,`animals`,`河马`],[`🦜`,`parrot`,`animals`,`鹦鹉`],[`🦝`,`raccoon`,`animals`,`浣熊`],[`🦞`,`lobster`,`animals`,`龙虾,海鲜`],[`🦟`,`mosquito`,`animals`,``],[`🦠`,`microbe`,`animals`,``],[`🦡`,`badger`,`animals`,`獾`],[`🦢`,`swan`,`animals`,`天鹅,鹅`],[`🦣`,`mammoth`,`animals`,`猛犸象`],[`🦤`,`dodo`,`animals`,`渡渡鸟`],[`🦥`,`sloth`,`animals`,`树懒`],[`🦦`,`otter`,`animals`,`水獭`],[`🦧`,`orangutan`,`animals`,``],[`🦨`,`skunk`,`animals`,`臭鼬`],[`🦩`,`flamingo`,`animals`,`火烈鸟,红鹤`],[`🦪`,`oyster`,`animals`,`生蚝,牡蛎`],[`🦫`,`beaver`,`animals`,`河狸,海狸`],[`🦬`,`bison`,`animals`,`野牛,水牛`],[`🦭`,`seal`,`animals`,`海豹,海狮`],[`🦮`,`guide dog`,`animals`,`导盲犬,狗`],[`🦯`,`probing cane`,`symbols`,``],[`🦰`,`emoji component red hair`,`people`,`红发,头发,发色`],[`🦱`,`emoji component curly hair`,`people`,`卷发,头发`],[`🦲`,`emoji component bald`,`people`,`光头,秃头`],[`🦳`,`emoji component white hair`,`people`,`白发,头发`],[`🦴`,`bone`,`people`,``],[`🦵`,`leg`,`people`,`腿,大腿`],[`🦶`,`foot`,`people`,`脚,足`],[`🦷`,`tooth`,`people`,`牙齿,牙`],[`🦸`,`superhero`,`people`,`英雄`],[`🦹`,`supervillain`,`people`,`超级反派,坏人,反派`],[`🦺`,`safety vest`,`symbols`,``],[`🦻`,`ear with hearing aid`,`symbols`,`助听器,耳朵`],[`🦼`,`motorized wheelchair`,`people`,``],[`🦽`,`manual wheelchair`,`people`,``],[`🦾`,`mechanical arm`,`people`,`机械臂,机器人,义肢`],[`🦿`,`mechanical leg`,`people`,`机械腿,义肢`],[`🧀`,`cheese wedge`,`food`,`奶酪,芝士`],[`🧁`,`cupcake`,`food`,`纸杯蛋糕,杯子蛋糕`],[`🧂`,`salt shaker`,`food`,``],[`🧃`,`beverage box`,`food`,`果汁盒,饮料`],[`🧄`,`garlic`,`food`,`大蒜,蒜`],[`🧅`,`onion`,`food`,`洋葱`],[`🧆`,`falafel`,`food`,`鹰嘴豆丸子`],[`🧇`,`waffle`,`food`,`华夫饼`],[`🧈`,`butter`,`food`,`黄油,奶油`],[`🧉`,`mate drink`,`food`,`马黛茶`],[`🧊`,`ice cube`,`food`,`冰块,冰`],[`🧋`,`bubble tea`,`food`,`奶茶,珍珠奶茶`],[`🧌`,`troll`,`symbols`,`巨魔,妖怪`],[`🧍`,`standing person`,`symbols`,`站立,站着,人`],[`🧎`,`kneeling person`,`symbols`,`跪,跪下,祈祷`],[`🧏`,`deaf person`,`symbols`,``],[`🧐`,`face with monocle`,`people`,`检查,研究,眼镜`],[`🧑`,`adult`,`people`,`人`],[`🧒`,`child`,`people`,``],[`🧓`,`older adult`,`people`,`老人,奶奶,爷爷`],[`🧔`,`bearded person`,`people`,`胡子,胡须,大叔`],[`🧕`,`person with headscarf`,`people`,`头巾`],[`🧖`,`person in steamy room`,`people`,`桑拿,蒸汽,洗澡`],[`🧗`,`person climbing`,`people`,`攀岩`],[`🧘`,`person in lotus position`,`people`,`打坐`],[`🧙`,`mage`,`people`,`巫师,魔法师,法师`],[`🧚`,`fairy`,`people`,`仙女,精灵,小仙女`],[`🧛`,`vampire`,`people`,`吸血鬼,德古拉`],[`🧜`,`merperson`,`people`,`美人鱼,人鱼`],[`🧝`,`elf`,`people`,`精灵,耳朵`],[`🧞`,`genie`,`people`,`灯神,精灵,神灯`],[`🧟`,`zombie`,`people`,`僵尸,丧尸`],[`🧠`,`brain`,`people`,`大脑,思考,记忆,AI`],[`🧡`,`orange heart`,`people`,``],[`🧢`,`billed cap`,`people`,`棒球帽,帽子`],[`🧣`,`scarf`,`people`,`围巾,冬天`],[`🧤`,`gloves`,`people`,`手套,冬天`],[`🧥`,`coat`,`people`,`大衣,外套`],[`🧦`,`socks`,`people`,`袜子`],[`🧧`,`red gift envelope`,`objects`,`红包,利是,新年`],[`🧨`,`firecracker`,`objects`,``],[`🧩`,`jigsaw puzzle piece`,`objects`,`拼图,拼图游戏`],[`🧪`,`test tube`,`objects`,`试管,实验,化学,科学`],[`🧫`,`petri dish`,`objects`,`培养皿,实验,细菌`],[`🧬`,`dna double helix`,`objects`,`DNA,基因,生物`],[`🧭`,`compass`,`objects`,`指南针`],[`🧮`,`abacus`,`objects`,`算盘,计算`],[`🧯`,`fire extinguisher`,`objects`,`灭火器,消防`],[`🧰`,`toolbox`,`objects`,`工具箱,工具`],[`🧱`,`brick`,`objects`,`砖`],[`🧲`,`magnet`,`objects`,`磁铁,磁性`],[`🧳`,`luggage`,`objects`,`行李箱`],[`🧴`,`lotion bottle`,`objects`,`乳液,护肤,防晒`],[`🧵`,`spool of thread`,`objects`,`线,针线,缝纫`],[`🧶`,`ball of yarn`,`objects`,`毛线,织毛衣`],[`🧷`,`safety pin`,`objects`,`别针,安全别针`],[`🧸`,`teddy bear`,`objects`,`泰迪熊,玩具熊`],[`🧹`,`broom`,`objects`,`扫帚`],[`🧺`,`basket`,`objects`,`篮子`],[`🧻`,`roll of paper`,`objects`,`纸巾`],[`🧼`,`bar of soap`,`objects`,`肥皂,洗手,清洁`],[`🧽`,`sponge`,`objects`,`海绵,清洁`],[`🧾`,`receipt`,`objects`,`收据`],[`🧿`,`nazar amulet`,`objects`,`护身符`],[`🩰`,`ballet shoes`,`activity`,`芭蕾`],[`🩱`,`one-piece swimsuit`,`activity`,`泳衣`],[`🩲`,`briefs`,`activity`,`泳裤`],[`🩳`,`shorts`,`activity`,`短裤`],[`🩴`,`thong sandal`,`activity`,`凉拖`],[`🩵`,`light blue heart`,`activity`,`浅蓝`],[`🩶`,`grey heart`,`activity`,`灰心`],[`🩷`,`pink heart`,`activity`,`粉色`],[`🩸`,`drop of blood`,`activity`,`血`],[`🩹`,`adhesive bandage`,`activity`,`创可贴`],[`🩺`,`stethoscope`,`activity`,`听诊器`],[`🩻`,`x-ray`,`activity`,`X光`],[`🩼`,`crutch`,`activity`,`拐杖`],[`🪀`,`yo-yo`,`objects`,`玩具`],[`🪁`,`kite`,`objects`,`风筝`],[`🪂`,`parachute`,`objects`,`跳伞`],[`🪃`,`boomerang`,`objects`,``],[`🪄`,`magic wand`,`objects`,`魔杖,魔法,魔术`],[`🪅`,`pinata`,`objects`,`皮纳塔`],[`🪆`,`nesting dolls`,`objects`,``],[`🪇`,`maracas`,`objects`,`沙锤`],[`🪈`,`flute`,`objects`,`笛子`],[`🪐`,`ringed planet`,`objects`,``],[`🪑`,`chair`,`objects`,`椅子`],[`🪒`,`razor`,`objects`,`剃须刀,剃刀`],[`🪓`,`axe`,`objects`,`斧头,斧子`],[`🪔`,`diya lamp`,`objects`,`油灯`],[`🪕`,`banjo`,`objects`,`班卓琴`],[`🪖`,`military helmet`,`objects`,`军盔`],[`🪗`,`accordion`,`objects`,`手风琴`],[`🪘`,`long drum`,`objects`,`鼓`],[`🪙`,`coin`,`objects`,`金币`],[`🪚`,`carpentry saw`,`objects`,`锯子,锯`],[`🪛`,`screwdriver`,`objects`,`螺丝刀`],[`🪜`,`ladder`,`objects`,`梯子`],[`🪝`,`hook`,`objects`,`钩子,挂钩`],[`🪞`,`mirror`,`objects`,`镜子`],[`🪟`,`window`,`objects`,`窗户`],[`🪠`,`plunger`,`objects`,`皮搋子,通马桶`],[`🪡`,`sewing needle`,`objects`,`针,缝纫,刺绣`],[`🪢`,`knot`,`objects`,``],[`🪣`,`bucket`,`objects`,`水桶,桶`],[`🪤`,`mouse trap`,`objects`,`捕鼠器`],[`🪥`,`toothbrush`,`objects`,`牙刷,刷牙`],[`🪦`,`headstone`,`objects`,`墓碑`],[`🪧`,`placard`,`objects`,`告示牌`],[`🪨`,`rock`,`objects`,`石头,岩石`],[`🪩`,`mirror ball`,`objects`,`迪斯科球`],[`🪪`,`identification card`,`objects`,`身份证`],[`🪫`,`low battery`,`objects`,`电池,没电,低电量`],[`🪬`,`hamsa`,`objects`,`手掌印,护身符`],[`🪭`,`folding hand fan`,`objects`,``],[`🪮`,`hair pick`,`objects`,`梳子`],[`🪯`,`khanda`,`objects`,``],[`🪰`,`fly`,`objects`,`苍蝇,飞虫`],[`🪱`,`worm`,`objects`,``],[`🪲`,`beetle`,`objects`,`甲虫,昆虫`],[`🪳`,`cockroach`,`objects`,`蟑螂,虫子`],[`🪴`,`potted plant`,`objects`,`盆栽,植物,绿植`],[`🪵`,`wood`,`objects`,`木头,柴火,木`],[`🪶`,`feather`,`objects`,`羽毛,羽毛笔`],[`🪷`,`lotus`,`objects`,`莲花`],[`🪸`,`coral`,`objects`,`珊瑚`],[`🪹`,`empty nest`,`objects`,`鸟巢`],[`🪺`,`nest with eggs`,`objects`,`鸟巢`],[`🪻`,`hyacinth`,`objects`,`风信子`],[`🪼`,`jellyfish`,`objects`,`水母`],[`🪽`,`wing`,`objects`,`翅膀`],[`🪿`,`goose`,`objects`,`鹅`],[`🫀`,`anatomical heart`,`objects`,`心脏,心跳`],[`🫁`,`lungs`,`objects`,`肺,呼吸`],[`🫂`,`people hugging`,`objects`,`拥抱,人,朋友`],[`🫃`,`pregnant man`,`objects`,`孕妇,怀孕`],[`🫄`,`pregnant person`,`objects`,`孕妇,怀孕`],[`🫅`,`person with crown`,`objects`,`国王,王子,皇冠`],[`🫎`,`moose`,`objects`,`驼鹿,麋鹿`],[`🫏`,`donkey`,`objects`,`驴,动物`],[`🫐`,`blueberries`,`food`,`蓝莓`],[`🫑`,`bell pepper`,`food`,`甜椒,彩椒`],[`🫒`,`olive`,`food`,`橄榄`],[`🫓`,`flatbread`,`food`,`薄饼,饼`],[`🫔`,`tamale`,`food`,`玉米粉蒸肉`],[`🫕`,`fondue`,`food`,`奶酪火锅`],[`🫖`,`teapot`,`food`,`茶壶,茶`],[`🫗`,`pouring liquid`,`food`,`倒,倒水,水杯`],[`🫘`,`beans`,`food`,`豆子,红豆`],[`🫙`,`jar`,`food`,`罐子,玻璃罐`],[`🫚`,`ginger root`,`food`,`姜,生姜`],[`🫛`,`pea pod`,`food`,`豌豆荚,豆`],[`🫠`,`melting face`,`smileys`,`融化`],[`🫡`,`saluting face`,`smileys`,`敬礼`],[`🫢`,`face with open eyes and hand over mouth`,`smileys`,`捂眼`],[`🫣`,`face with peeking eye`,`smileys`,`偷看`],[`🫤`,`face with diagonal mouth`,`smileys`,`撇嘴`],[`🫥`,`dotted line face`,`smileys`,`隐形`],[`🫦`,`biting lip`,`smileys`,`咬唇,嘴唇`],[`🫧`,`bubbles`,`smileys`,`泡泡`],[`🫨`,`shaking face`,`smileys`,`摇晃,震动,抖`],[`🫰`,`hand with index finger and thumb crossed`,`people`,`比心,手指,捏`],[`🫱`,`rightwards hand`,`people`,`手,右边,推`],[`🫲`,`leftwards hand`,`people`,`手,左边,推`],[`🫳`,`palm down hand`,`people`,`手,向下,放`],[`🫴`,`palm up hand`,`people`,`手,向上,举`],[`🫵`,`index pointing at the viewer`,`people`,`指,你`],[`🫶`,`heart hands`,`people`,`比心,爱心,手势`],[`🫷`,`leftwards pushing hand`,`people`,`手,推,右边`],[`🫸`,`rightwards pushing hand`,`people`,`手,推,左边`],[`‼`,`double exclamation mark`,`symbols`,``],[`‼️`,`double exclamation mark`,`symbols`,``],[`⁉`,`exclamation question mark`,`symbols`,``],[`⁉️`,`exclamation question mark`,`symbols`,``],[`™`,`trade mark sign`,`symbols`,``],[`™️`,`trade mark sign`,`symbols`,``],[`ℹ`,`information source`,`symbols`,``],[`ℹ️`,`information source`,`symbols`,``],[`↔`,`left right arrow`,`symbols`,``],[`↔️`,`left right arrow`,`symbols`,``],[`↕`,`up down arrow`,`symbols`,``],[`↕️`,`up down arrow`,`symbols`,``],[`↖`,`north west arrow`,`symbols`,``],[`↖️`,`north west arrow`,`symbols`,``],[`↗`,`north east arrow`,`symbols`,``],[`↗️`,`north east arrow`,`symbols`,``],[`↘`,`south east arrow`,`symbols`,``],[`↘️`,`south east arrow`,`symbols`,``],[`↙`,`south west arrow`,`symbols`,``],[`↙️`,`south west arrow`,`symbols`,``],[`↩`,`leftwards arrow with hook`,`symbols`,``],[`↩️`,`leftwards arrow with hook`,`symbols`,``],[`↪`,`rightwards arrow with hook`,`symbols`,``],[`↪️`,`rightwards arrow with hook`,`symbols`,``],[`⌚`,`watch`,`objects`,`手表`],[`⌚️`,`watch`,`objects`,``],[`⌛`,`hourglass`,`objects`,`沙漏,时间,等待`],[`⌛️`,`hourglass`,`objects`,``],[`⌨`,`keyboard`,`symbols`,``],[`⌨️`,`keyboard`,`symbols`,`键盘,打字`],[`⏏`,`eject symbol`,`symbols`,``],[`⏏️`,`eject symbol`,`symbols`,``],[`⏩`,`black right-pointing double triangle`,`objects`,``],[`⏪`,`black left-pointing double triangle`,`objects`,``],[`⏫`,`black up-pointing double triangle`,`objects`,``],[`⏬`,`black down-pointing double triangle`,`objects`,``],[`⏭`,`black right-pointing double triangle with vertical bar`,`objects`,``],[`⏭️`,`black right-pointing double triangle with vertical bar`,`objects`,``],[`⏮`,`black left-pointing double triangle with vertical bar`,`objects`,``],[`⏮️`,`black left-pointing double triangle with vertical bar`,`objects`,``],[`⏯`,`black right-pointing triangle with double vertical bar`,`objects`,``],[`⏯️`,`black right-pointing triangle with double vertical bar`,`objects`,``],[`⏰`,`alarm clock`,`objects`,`闹钟,时间,起床`],[`⏱`,`stopwatch`,`objects`,``],[`⏱️`,`stopwatch`,`objects`,`秒表`],[`⏲`,`timer clock`,`objects`,``],[`⏲️`,`timer clock`,`objects`,`计时器`],[`⏳`,`hourglass with flowing sand`,`objects`,`沙漏`],[`⏸`,`double vertical bar`,`symbols`,``],[`⏸️`,`double vertical bar`,`symbols`,``],[`⏹`,`black square for stop`,`symbols`,``],[`⏹️`,`black square for stop`,`symbols`,``],[`⏺`,`black circle for record`,`symbols`,``],[`⏺️`,`black circle for record`,`symbols`,``],[`Ⓜ`,`circled latin capital letter m`,`symbols`,``],[`Ⓜ️`,`circled latin capital letter m`,`symbols`,``],[`▪`,`black small square`,`symbols`,``],[`▪️`,`black small square`,`symbols`,``],[`▫`,`white small square`,`symbols`,``],[`▫️`,`white small square`,`symbols`,``],[`▶`,`black right-pointing triangle`,`symbols`,``],[`▶️`,`black right-pointing triangle`,`symbols`,``],[`◀`,`black left-pointing triangle`,`symbols`,``],[`◀️`,`black left-pointing triangle`,`symbols`,``],[`◻`,`white medium square`,`symbols`,``],[`◻️`,`white medium square`,`symbols`,``],[`◼`,`black medium square`,`symbols`,``],[`◼️`,`black medium square`,`symbols`,``],[`◽`,`white medium small square`,`symbols`,``],[`◾`,`black medium small square`,`symbols`,``],[`◾️`,`black medium small square`,`symbols`,``],[`☀`,`black sun with rays`,`symbols`,``],[`☀️`,`black sun with rays`,`symbols`,`太阳,晴天,阳光`],[`☁`,`cloud`,`symbols`,``],[`☁️`,`cloud`,`symbols`,`云,多云,天气`],[`☂`,`umbrella`,`symbols`,``],[`☂️`,`umbrella`,`symbols`,``],[`☃`,`snowman`,`symbols`,``],[`☃️`,`snowman`,`symbols`,`雪人,冬天,雪`],[`☄`,`comet`,`symbols`,``],[`☄️`,`comet`,`symbols`,``],[`☎`,`black telephone`,`symbols`,``],[`☎️`,`black telephone`,`symbols`,`电话`],[`☑`,`ballot box with check`,`symbols`,``],[`☑️`,`ballot box with check`,`symbols`,``],[`☔`,`umbrella with rain drops`,`symbols`,``],[`☔️`,`umbrella with rain drops`,`symbols`,``],[`☕`,`hot beverage`,`food`,`咖啡,热饮`],[`☕️`,`hot beverage`,`food`,``],[`☘`,`shamrock`,`symbols`,``],[`☘️`,`shamrock`,`symbols`,``],[`☝`,`white up pointing index`,`symbols`,``],[`☝️`,`white up pointing index`,`symbols`,`指,上面,向上`],[`☠`,`skull and crossbones`,`symbols`,``],[`☠️`,`skull and crossbones`,`symbols`,`骷髅,死亡,危险`],[`☢`,`radioactive sign`,`symbols`,``],[`☢️`,`radioactive sign`,`symbols`,``],[`☣`,`biohazard sign`,`symbols`,``],[`☣️`,`biohazard sign`,`symbols`,``],[`☦`,`orthodox cross`,`symbols`,``],[`☦️`,`orthodox cross`,`symbols`,``],[`☪`,`star and crescent`,`symbols`,``],[`☪️`,`star and crescent`,`symbols`,``],[`☮`,`peace symbol`,`symbols`,``],[`☮️`,`peace symbol`,`symbols`,``],[`☯`,`yin yang`,`symbols`,``],[`☯️`,`yin yang`,`symbols`,``],[`☸`,`wheel of dharma`,`symbols`,``],[`☸️`,`wheel of dharma`,`symbols`,``],[`☹`,`white frowning face`,`smileys`,``],[`☹️`,`white frowning face`,`smileys`,``],[`☺`,`white smiling face`,`smileys`,``],[`☺️`,`white smiling face`,`smileys`,``],[`♀`,`female sign`,`symbols`,``],[`♀️`,`female sign`,`symbols`,``],[`♂`,`male sign`,`symbols`,``],[`♂️`,`male sign`,`symbols`,``],[`♈`,`aries`,`symbols`,``],[`♈️`,`aries`,`symbols`,``],[`♉`,`taurus`,`symbols`,``],[`♉️`,`taurus`,`symbols`,``],[`♊`,`gemini`,`symbols`,``],[`♊️`,`gemini`,`symbols`,``],[`♋`,`cancer`,`symbols`,``],[`♋️`,`cancer`,`symbols`,``],[`♌`,`leo`,`symbols`,``],[`♌️`,`leo`,`symbols`,``],[`♍`,`virgo`,`symbols`,``],[`♍️`,`virgo`,`symbols`,``],[`♎`,`libra`,`symbols`,``],[`♎️`,`libra`,`symbols`,``],[`♏`,`scorpius`,`symbols`,``],[`♏️`,`scorpius`,`symbols`,``],[`♐`,`sagittarius`,`symbols`,``],[`♐️`,`sagittarius`,`symbols`,``],[`♑`,`capricorn`,`symbols`,``],[`♑️`,`capricorn`,`symbols`,``],[`♒`,`aquarius`,`symbols`,``],[`♒️`,`aquarius`,`symbols`,``],[`♓`,`pisces`,`symbols`,``],[`♓️`,`pisces`,`symbols`,``],[`♟`,`black chess pawn`,`symbols`,``],[`♟️`,`black chess pawn`,`symbols`,`棋子,国际象棋,象棋`],[`♠`,`black spade suit`,`symbols`,``],[`♠️`,`black spade suit`,`symbols`,``],[`♣`,`black club suit`,`symbols`,``],[`♣️`,`black club suit`,`symbols`,``],[`♥`,`black heart suit`,`symbols`,``],[`♥️`,`black heart suit`,`symbols`,``],[`♦`,`black diamond suit`,`symbols`,``],[`♦️`,`black diamond suit`,`symbols`,``],[`♨`,`hot springs`,`symbols`,``],[`♨️`,`hot springs`,`symbols`,`温泉,热泉`],[`♻`,`black universal recycling symbol`,`symbols`,``],[`♻️`,`black universal recycling symbol`,`symbols`,``],[`♾`,`permanent paper sign`,`symbols`,``],[`♾️`,`permanent paper sign`,`symbols`,``],[`♿`,`wheelchair symbol`,`symbols`,``],[`♿️`,`wheelchair symbol`,`symbols`,``],[`⚒`,`hammer and pick`,`symbols`,``],[`⚒️`,`hammer and pick`,`symbols`,`锤子,工具`],[`⚓`,`anchor`,`symbols`,`锚,航海,停泊`],[`⚔`,`crossed swords`,`symbols`,``],[`⚔️`,`crossed swords`,`symbols`,`剑,交叉,战斗`],[`⚕`,`staff of aesculapius`,`symbols`,``],[`⚕️`,`staff of aesculapius`,`symbols`,``],[`⚖`,`scales`,`symbols`,``],[`⚖️`,`scales`,`symbols`,``],[`⚗`,`alembic`,`symbols`,``],[`⚗️`,`alembic`,`symbols`,``],[`⚙`,`gear`,`symbols`,``],[`⚙️`,`gear`,`symbols`,``],[`⚛`,`atom symbol`,`symbols`,``],[`⚛️`,`atom symbol`,`symbols`,``],[`⚜`,`fleur-de-lis`,`symbols`,``],[`⚜️`,`fleur-de-lis`,`symbols`,``],[`⚠`,`warning sign`,`symbols`,``],[`⚠️`,`warning sign`,`symbols`,``],[`⚡`,`high voltage sign`,`symbols`,``],[`⚧`,`male with stroke and male and female sign`,`symbols`,``],[`⚧️`,`male with stroke and male and female sign`,`symbols`,``],[`⚪`,`medium white circle`,`symbols`,``],[`⚪️`,`medium white circle`,`symbols`,``],[`⚫`,`medium black circle`,`symbols`,``],[`⚰`,`coffin`,`symbols`,``],[`⚰️`,`coffin`,`symbols`,`棺材,死亡`],[`⚱`,`funeral urn`,`symbols`,``],[`⚱️`,`funeral urn`,`symbols`,`骨灰盒,死亡`],[`⚽`,`soccer ball`,`activity`,`足球,球`],[`⚽️`,`soccer ball`,`activity`,``],[`⚾`,`baseball`,`activity`,`棒球,球`],[`⚾️`,`baseball`,`activity`,``],[`⛄`,`snowman without snow`,`symbols`,`雪人,冬天`],[`⛄️`,`snowman without snow`,`symbols`,``],[`⛅`,`sun behind cloud`,`symbols`,`太阳,云,多云`],[`⛈`,`thunder cloud and rain`,`symbols`,``],[`⛈️`,`thunder cloud and rain`,`symbols`,`雷雨,雷暴,天气`],[`⛎`,`ophiuchus`,`symbols`,``],[`⛏`,`pick`,`symbols`,``],[`⛏️`,`pick`,`symbols`,`镐,工具`],[`⛑`,`helmet with white cross`,`symbols`,``],[`⛑️`,`helmet with white cross`,`symbols`,`头盔,救援,安全`],[`⛓`,`chains`,`symbols`,``],[`⛓️`,`chains`,`symbols`,``],[`⛔`,`no entry`,`symbols`,``],[`⛩`,`shinto shrine`,`travel`,``],[`⛩️`,`shinto shrine`,`travel`,`鸟居,神社,日本`],[`⛪`,`church`,`travel`,`教堂`],[`⛰`,`mountain`,`travel`,``],[`⛰️`,`mountain`,`travel`,`山,山峰`],[`⛱`,`umbrella on ground`,`travel`,``],[`⛱️`,`umbrella on ground`,`travel`,``],[`⛲`,`fountain`,`travel`,`喷泉`],[`⛲️`,`fountain`,`travel`,``],[`⛳`,`flag in hole`,`activity`,`高尔夫,高尔夫球,球洞`],[`⛳️`,`flag in hole`,`activity`,``],[`⛴`,`ferry`,`travel`,``],[`⛴️`,`ferry`,`travel`,`渡轮,船`],[`⛵`,`sailboat`,`travel`,`帆船,船`],[`⛵️`,`sailboat`,`travel`,``],[`⛷`,`skier`,`activity`,``],[`⛷️`,`skier`,`activity`,``],[`⛸`,`ice skate`,`activity`,``],[`⛸️`,`ice skate`,`activity`,`溜冰,冰刀,滑冰`],[`⛹`,`person with ball`,`activity`,``],[`⛹️`,`person with ball`,`activity`,``],[`⛺`,`tent`,`travel`,`帐篷,露营`],[`⛺️`,`tent`,`travel`,``],[`⛽`,`fuel pump`,`travel`,`加油站,加油,汽油`],[`✂`,`black scissors`,`symbols`,``],[`✂️`,`black scissors`,`symbols`,``],[`✅`,`white heavy check mark`,`symbols`,``],[`✈`,`airplane`,`travel`,``],[`✈️`,`airplane`,`travel`,`飞机,航班,起飞`],[`✉`,`envelope`,`symbols`,``],[`✉️`,`envelope`,`symbols`,`信封,邮件,信`],[`✊`,`raised fist`,`people`,`拳头,加油,力量`],[`✋`,`raised hand`,`people`,`手,举手,停`],[`✌`,`victory hand`,`symbols`,``],[`✌️`,`victory hand`,`symbols`,`胜利,耶,剪刀手`],[`✍`,`writing hand`,`symbols`,``],[`✍️`,`writing hand`,`symbols`,`写字,写作,手`],[`✏`,`pencil`,`symbols`,``],[`✏️`,`pencil`,`symbols`,``],[`✒`,`black nib`,`symbols`,``],[`✒️`,`black nib`,`symbols`,``],[`✔`,`heavy check mark`,`symbols`,``],[`✔️`,`heavy check mark`,`symbols`,``],[`✖`,`heavy multiplication x`,`symbols`,``],[`✖️`,`heavy multiplication x`,`symbols`,``],[`✝`,`latin cross`,`symbols`,``],[`✝️`,`latin cross`,`symbols`,``],[`✡`,`star of david`,`symbols`,``],[`✡️`,`star of david`,`symbols`,``],[`✨`,`sparkles`,`symbols`,`星星,闪光,发光`],[`✳`,`eight spoked asterisk`,`symbols`,``],[`✳️`,`eight spoked asterisk`,`symbols`,``],[`✴`,`eight pointed black star`,`symbols`,``],[`✴️`,`eight pointed black star`,`symbols`,``],[`❄`,`snowflake`,`symbols`,``],[`❄️`,`snowflake`,`symbols`,`雪花,雪,冬天,冷`],[`❇`,`sparkle`,`symbols`,``],[`❇️`,`sparkle`,`symbols`,``],[`❌`,`cross mark`,`symbols`,``],[`❎`,`negative squared cross mark`,`symbols`,``],[`❓`,`black question mark ornament`,`symbols`,``],[`❔`,`white question mark ornament`,`symbols`,``],[`❕`,`white exclamation mark ornament`,`symbols`,``],[`❗`,`heavy exclamation mark symbol`,`symbols`,``],[`❗️`,`heavy exclamation mark symbol`,`symbols`,``],[`❣`,`heavy heart exclamation mark ornament`,`symbols`,``],[`❣️`,`heavy heart exclamation mark ornament`,`symbols`,`爱心,感叹号`],[`❤`,`heavy black heart`,`smileys`,``],[`❤️`,`heavy black heart`,`smileys`,`爱心,红心,爱`],[`➕`,`heavy plus sign`,`symbols`,``],[`➖`,`heavy minus sign`,`symbols`,``],[`➗`,`heavy division sign`,`symbols`,``],[`➡`,`black rightwards arrow`,`symbols`,``],[`➡️`,`black rightwards arrow`,`symbols`,``],[`➰`,`curly loop`,`symbols`,``],[`➿`,`double curly loop`,`symbols`,``],[`⬅`,`leftwards black arrow`,`symbols`,``],[`⬅️`,`leftwards black arrow`,`symbols`,``],[`⬆`,`upwards black arrow`,`symbols`,``],[`⬆️`,`upwards black arrow`,`symbols`,``],[`⬇`,`downwards black arrow`,`symbols`,``],[`⬇️`,`downwards black arrow`,`symbols`,``],[`⬛`,`black large square`,`symbols`,``],[`⬛️`,`black large square`,`symbols`,``],[`⬜`,`white large square`,`symbols`,``],[`⬜️`,`white large square`,`symbols`,``],[`⭐`,`white medium star`,`symbols`,`星星,五星,评分`],[`⭕`,`heavy large circle`,`symbols`,``],[`⭕️`,`heavy large circle`,`symbols`,``],[`⤴`,`arrow pointing rightwards then curving upwards`,`symbols`,``],[`⤴️`,`arrow pointing rightwards then curving upwards`,`symbols`,``],[`⤵`,`arrow pointing rightwards then curving downwards`,`symbols`,``],[`⤵️`,`arrow pointing rightwards then curving downwards`,`symbols`,``],[`〰`,`wavy dash`,`symbols`,``],[`〰️`,`wavy dash`,`symbols`,``],[`〽`,`part alternation mark`,`symbols`,``],[`〽️`,`part alternation mark`,`symbols`,``],[`㊗`,`circled ideograph congratulation`,`symbols`,``],[`㊗️`,`circled ideograph congratulation`,`symbols`,``],[`㊙`,`circled ideograph secret`,`symbols`,``],[`㊙️`,`circled ideograph secret`,`symbols`,``],[`©`,`copyright sign`,`symbols`,``],[`©️`,`copyright sign`,`symbols`,``],[`®`,`registered sign`,`symbols`,``],[`®️`,`registered sign`,`symbols`,``],[`👨💻`,`man technologist`,`people`,`程序员,开发者,工程师,码农`],[`👩💻`,`woman technologist`,`people`,`程序员,开发者,工程师`],[`🧑💻`,`technologist`,`people`,`程序员,开发者,工程师`],[`👨🔧`,`man mechanic`,`people`,``],[`👩🔧`,`woman mechanic`,`people`,``],[`👨🎨`,`man artist`,`people`,``],[`👩🎨`,`woman artist`,`people`,``],[`👨🚀`,`man astronaut`,`people`,``],[`👩🚀`,`woman astronaut`,`people`,``],[`👨⚕️`,`man health worker`,`people`,``],[`👩⚕️`,`woman health worker`,`people`,``],[`👨🏫`,`man teacher`,`people`,``],[`👩🏫`,`woman teacher`,`people`,``],[`👨🍳`,`man cook`,`people`,``],[`👩🍳`,`woman cook`,`people`,``],[`👨🌾`,`man farmer`,`people`,``],[`👩🌾`,`woman farmer`,`people`,``],[`👩🏭`,`woman factory worker`,`people`,``],[`👨🎓`,`man student`,`people`,``],[`👩🎓`,`woman student`,`people`,``],[`👨🚒`,`man firefighter`,`people`,``],[`👩🚒`,`woman firefighter`,`people`,``],[`👨⚖️`,`man judge`,`people`,``],[`👩⚖️`,`woman judge`,`people`,``],[`👨💼`,`man office worker`,`people`,``],[`👩💼`,`woman office worker`,`people`,``],[`👨🎤`,`man singer`,`people`,``],[`👩🎤`,`woman singer`,`people`,``],[`👨🦰`,`man red hair`,`people`,``],[`👩🦰`,`woman red hair`,`people`,``],[`👨🦱`,`man curly hair`,`people`,``],[`👩🦱`,`woman curly hair`,`people`,``],[`👩🦲`,`woman bald`,`people`,``],[`👨🦳`,`man white hair`,`people`,``],[`👩🦳`,`woman white hair`,`people`,``],[`👩❤️👨`,`couple with heart`,`people`,``],[`👨❤️👨`,`couple with heart`,`people`,``],[`👩❤️👩`,`couple with heart`,`people`,``],[`👨👩👧`,`family man woman girl`,`people`,``],[`👨👩👦`,`family man woman boy`,`people`,``],[`👨👩👧👦`,`family man woman girl boy`,`people`,``],[`👨👩👦👦`,`man`,`people`,``],[`👨👩👧👧`,`family man woman girl girl`,`people`,``],[`👩👩👧`,`family woman woman girl`,`people`,``],[`👨👨👧`,`family man man girl`,`people`,``],[`👨👦`,`family man boy`,`people`,``],[`👩👧`,`family woman girl`,`people`,``],[`👨👧👦`,`family man girl boy`,`people`,``],[`👩❤️💋👨`,`kiss woman man`,`people`,``],[`🧑🤝🧑`,`people holding hands`,`people`,``],[`❤️🔥`,`heart on fire`,`smileys`,``],[`🧑🚒`,`firefighter`,`people`,`消防员`],[`🧑🏭`,`factory worker`,`people`,``],[`🧑🎓`,`student`,`people`,`学生,毕业生,大学生`],[`🧑🏫`,`teacher`,`people`,`老师,教师,教授`],[`🧑🎤`,`singer`,`people`,`歌手,歌星`],[`🧑⚕️`,`health worker`,`people`,`医生,医疗`],[`🧑⚖️`,`judge`,`people`,`法官,审判`],[`🧑🍳`,`cook`,`people`,`厨师,大厨`],[`🧑🌾`,`farmer`,`people`,`农民,农夫`],[`🧑🎨`,`artist`,`people`,`画家,艺术家`],[`🧑🔬`,`scientist`,`people`,``],[`🧑🔧`,`mechanic`,`people`,`技工,维修工`],[`🧑💼`,`office worker`,`people`,`白领,上班族,职员`],[`🧑🚀`,`astronaut`,`people`,`宇航员,太空人`],[`🏃♂️`,`man running`,`activity`,``],[`🏃♀️`,`woman running`,`activity`,``],[`🚶♂️`,`man walking`,`travel`,``],[`🚶♀️`,`woman walking`,`travel`,``],[`🧎♂️`,`man kneeling`,`symbols`,``],[`🧎♀️`,`woman kneeling`,`symbols`,``],[`🏋️♂️`,`man lifting weights`,`activity`,``],[`🏋️♀️`,`woman lifting weights`,`activity`,``],[`🤸♂️`,`man cartwheeling`,`people`,``],[`🤸♀️`,`woman cartwheeling`,`people`,``],[`⛹️♂️`,`man bouncing ball`,`activity`,``],[`⛹️♀️`,`woman bouncing ball`,`activity`,``],[`🤾♂️`,`man playing handball`,`activity`,``],[`🤾♀️`,`woman playing handball`,`activity`,``],[`🧘♀️`,`woman in lotus position`,`people`,``],[`🏄♂️`,`man surfing`,`activity`,``],[`🏄♀️`,`woman surfing`,`activity`,``],[`🏊♂️`,`man swimming`,`activity`,``],[`🏊♀️`,`woman swimming`,`activity`,``],[`🚴♂️`,`man biking`,`travel`,``],[`🚴♀️`,`woman biking`,`travel`,``],[`🚵♂️`,`man mountain biking`,`travel`,``],[`🚵♀️`,`woman mountain biking`,`travel`,``],[`👯♂️`,`men with bunny ears`,`people`,``],[`👯♀️`,`women with bunny ears`,`people`,``],[`🧖♂️`,`man in steamy room`,`people`,``],[`🧖♀️`,`woman in steamy room`,`people`,``],[`🧗♂️`,`man climbing`,`people`,``],[`🧗♀️`,`woman climbing`,`people`,``],[`🤦♂️`,`man facepalming`,`smileys`,``],[`🤦♀️`,`woman facepalming`,`smileys`,``],[`🤷♂️`,`man shrugging`,`people`,``],[`🤷♀️`,`woman shrugging`,`people`,``],[`🙍♂️`,`person frowning`,`smileys`,``],[`🙍♀️`,`woman frowning`,`smileys`,``],[`🙎♂️`,`man pouting`,`smileys`,``],[`🙎♀️`,`woman pouting`,`smileys`,``],[`🙅♂️`,`man gesturing no`,`smileys`,``],[`🙅♀️`,`woman gesturing no`,`smileys`,``],[`🙆♂️`,`man gesturing ok`,`smileys`,``],[`🙆♀️`,`woman gesturing ok`,`smileys`,``],[`💁♂️`,`man tipping hand`,`people`,``],[`💁♀️`,`woman tipping hand`,`people`,``],[`🙋♂️`,`man raising hand`,`smileys`,``],[`🙋♀️`,`woman raising hand`,`smileys`,``],[`🙇♂️`,`man bowing`,`smileys`,``],[`🙇♀️`,`woman bowing`,`smileys`,``],[`💆♂️`,`man getting massage`,`people`,``],[`💆♀️`,`woman getting massage`,`people`,``],[`💇♂️`,`man getting haircut`,`people`,``],[`💇♀️`,`woman getting haircut`,`people`,``],[`🧞♂️`,`man genie`,`people`,``],[`🧞♀️`,`woman genie`,`people`,``],[`🧟♂️`,`man zombie`,`people`,``],[`🧟♀️`,`woman zombie`,`people`,``],[`🧜♂️`,`merman`,`people`,``],[`🧚♂️`,`man fairy`,`people`,``],[`🧚♀️`,`woman fairy`,`people`,``],[`🧛♂️`,`man vampire`,`people`,``],[`🧛♀️`,`woman vampire`,`people`,``],[`🧙♂️`,`man mage`,`people`,``],[`🧙♀️`,`mage`,`people`,``],[`🧝♂️`,`man elf`,`people`,``],[`🧝♀️`,`woman elf`,`people`,``],[`🦸♂️`,`man superhero`,`people`,``],[`🦸♀️`,`woman superhero`,`people`,``],[`🦹♂️`,`man supervillain`,`people`,``],[`🦹♀️`,`woman supervillain`,`people`,``],[`0️⃣`,`keycap 0`,`symbols`,``],[`1️⃣`,`keycap 1`,`symbols`,``],[`2️⃣`,`keycap 2`,`symbols`,``],[`3️⃣`,`keycap 3`,`symbols`,``],[`4️⃣`,`keycap 4`,`symbols`,``],[`5️⃣`,`keycap 5`,`symbols`,``],[`6️⃣`,`keycap 6`,`symbols`,``],[`7️⃣`,`keycap 7`,`symbols`,``],[`8️⃣`,`keycap 8`,`symbols`,``],[`9️⃣`,`keycap 9`,`symbols`,``],[`#️⃣`,`keycap #`,`symbols`,``],[`*️⃣`,`keycap *`,`symbols`,``],[`🇨🇳`,`flag china`,`flags`,`中国,国旗,五星红旗`],[`🇺🇸`,`flag united states`,`flags`,`美国,国旗,USA`],[`🇬🇧`,`flag united kingdom`,`flags`,`英国,国旗,UK`],[`🇯🇵`,`flag japan`,`flags`,`日本,国旗`],[`🇫🇷`,`flag france`,`flags`,`法国,国旗`],[`🇩🇪`,`flag germany`,`flags`,`德国,国旗`],[`🇮🇹`,`flag italy`,`flags`,`意大利,国旗`],[`🇪🇸`,`flag spain`,`flags`,`西班牙,国旗`],[`🇷🇺`,`flag russia`,`flags`,`俄罗斯,国旗`],[`🇮🇳`,`regional indicator symbol letter i`,`flags`,`印度,国旗`],[`🇧🇷`,`flag brazil`,`flags`,`巴西,国旗`],[`🇨🇦`,`flag canada`,`flags`,`加拿大,国旗`],[`🇦🇺`,`flag australia`,`flags`,`澳大利亚,国旗`],[`🇸🇬`,`flag singapore`,`flags`,`新加坡,国旗`],[`🇭🇰`,`flag hong kong`,`flags`,`香港,国旗,区旗`],[`🇹🇼`,`flag taiwan`,`flags`,`台湾,国旗`],[`🇲🇴`,`flag macau`,`flags`,`澳门,国旗`],[`🇻🇳`,`flag vietnam`,`flags`,`越南,国旗`],[`🇲🇾`,`regional indicator symbol letter m`,`flags`,`马来西亚,国旗`],[`🇮🇩`,`flag indonesia`,`flags`,`印尼,国旗`],[`🇵🇭`,`flag philippines`,`flags`,`菲律宾,国旗`],[`🇹🇷`,`flag turkey`,`flags`,`土耳其,国旗`],[`🇸🇦`,`flag saudi arabia`,`flags`,`沙特,国旗`],[`🇦🇪`,`flag united arab emirates`,`flags`,`阿联酋,国旗`],[`🇳🇱`,`flag netherlands`,`flags`,`荷兰,国旗`],[`🇸🇪`,`flag sweden`,`flags`,`瑞典,国旗`],[`🇨🇭`,`flag switzerland`,`flags`,`瑞士,国旗`],[`🇦🇹`,`flag austria`,`flags`,`奥地利,国旗`],[`🇧🇪`,`flag belgium`,`flags`,`比利时,国旗`],[`🇵🇹`,`flag portugal`,`flags`,`葡萄牙,国旗`],[`🇬🇷`,`flag greece`,`flags`,`希腊,国旗`],[`🇳🇴`,`flag norway`,`flags`,`挪威,国旗`],[`🇩🇰`,`flag denmark`,`flags`,`丹麦,国旗`],[`🇫🇮`,`flag finland`,`flags`,`芬兰,国旗`],[`🇵🇱`,`flag poland`,`flags`,`波兰,国旗`],[`🇺🇦`,`flag ukraine`,`flags`,`乌克兰,国旗`],[`🇮🇱`,`flag israel`,`flags`,`以色列,国旗`],[`🇪🇬`,`flag egypt`,`flags`,`埃及,国旗`],[`🇿🇦`,`flag south africa`,`flags`,`南非,国旗`],[`🇳🇬`,`flag nigeria`,`flags`,`尼日利亚,国旗`],[`🇲🇽`,`flag mexico`,`flags`,`墨西哥,国旗`],[`🇦🇷`,`flag argentina`,`flags`,``],[`🇨🇱`,`flag chile`,`flags`,`智利,国旗`],[`🇰🇿`,`flag kazakhstan`,`flags`,`哈萨克斯坦,国旗`],[`🇺🇿`,`flag uzbekistan`,`flags`,`乌兹别克斯坦,国旗`],[`🇳🇿`,`flag new zealand`,`flags`,`新西兰,国旗`],[`🇮🇪`,`flag ireland`,`flags`,`爱尔兰,国旗`],[`🇨🇿`,`flag czechia`,`flags`,`捷克,国旗`],[`👍🏻`,`thumbs up light skin`,`people`,``],[`👍🏽`,`thumbs up sign`,`people`,``],[`👍🏾`,`thumbs up medium dark skin`,`people`,``],[`👍🏿`,`thumbs up dark skin`,`people`,``],[`👏🏻`,`clapping hands light skin`,`people`,``],[`👏🏼`,`clapping hands medium light skin`,`people`,``],[`👏🏽`,`clapping hands medium skin`,`people`,``],[`👏🏾`,`clapping hands medium dark skin`,`people`,``],[`👏🏿`,`clapping hands dark skin`,`people`,``],[`🙏🏻`,`folded hands light skin`,`smileys`,``],[`🙏🏼`,`folded hands medium light skin`,`smileys`,``],[`🙏🏽`,`folded hands medium skin`,`smileys`,``],[`🙏🏾`,`folded hands medium dark skin`,`smileys`,``],[`🙏🏿`,`folded hands dark skin`,`smileys`,``],[`🏳️🌈`,`rainbow flag`,`flags`,``],[`🏴☠️`,`pirate flag`,`flags`,`海盗旗,海盗`]];n(`zh`,{agentMgr:{allTools:`全部`,defaultAgentName:`默认助手`,defaultAgentDesc:`全能 AI 助手,拥有所有工具能力`,switchedTo:`已切换到:{name}`,editAgent:`编辑助手`,templateLoaded:`已加载模板:{name}`,noSkillsHint:`暂无启用技能(请先确认 Agent 已连接且技能开关已开启)`,nameRequired:`请输入助手名称`,agentUpdated:`助手已更新`,agentCreated:`助手 "{name}" 已创建`,saveFailed:`保存失败:{message}`,confirmDeleteAgentMessage:`确定要删除助手 "{name}" 吗?
|
|
2073
2073
|
正在使用该助手的会话将恢复为默认助手。`,deleteAgentTitle:`删除助手`,agentDeleted:`助手已删除`,deleteFailed:`删除失败:{message}`,cannotDeleteDefault:`默认助手不支持删除`,emojiCatSmileys:`笑脸与表情`,emojiCatPeople:`人物与身体`,emojiCatAnimals:`动物与自然`,emojiCatFood:`食物与饮品`,emojiCatTravel:`旅行与交通`,emojiCatActivity:`活动与运动`,emojiCatObjects:`物品`,emojiCatSymbols:`符号`,emojiCatFlags:`旗帜`,emojiSearchPlaceholder:`搜索 Emoji(英文名 / 中文关键词)`,emojiSearchClear:`清空搜索`,emojiNoMatch:`未找到匹配的 Emoji`,confirm:`确认`},agentTemplates:{codeReviewName:`代码审查专家`,codeReviewDesc:`专注于代码审查和质量保证`,webAutomationName:`网页自动化助手`,webAutomationDesc:`专注于网页交互和自动化`,dataAnalystName:`数据分析师`,dataAnalystDesc:`专注于数据提取、分析和可视化`,documentationName:`文档助手`,documentationDesc:`专注于技术文档和内容整理`}}),n(`en`,{agentMgr:{allTools:`All`,defaultAgentName:`Default Assistant`,defaultAgentDesc:`All-purpose AI assistant with all tool capabilities`,switchedTo:`Switched to: {name}`,editAgent:`Edit assistant`,templateLoaded:`Template loaded: {name}`,noSkillsHint:`No enabled skills (please confirm Agent is connected and skill switch is on)`,nameRequired:`Please enter assistant name`,agentUpdated:`Assistant updated`,agentCreated:`Assistant "{name}" created`,saveFailed:`Save failed: {message}`,confirmDeleteAgentMessage:`Are you sure you want to delete assistant "{name}"?
|
|
@@ -2087,7 +2087,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2087
2087
|
<div class="agent-item" id="agentAddBtn" style="color:var(--brand-500);">
|
|
2088
2088
|
<span class="agent-item-icon" style="color:var(--brand-500);">+</span>
|
|
2089
2089
|
<span class="agent-item-name">${r(`agentEditor.createNew`)}</span>
|
|
2090
|
-
</div>`),ZT(n,i)}function ZT(e,t){let n=document.getElementById(`agentSelectorBtn`),i=document.getElementById(`agentSelectorText`),a=document.getElementById(`agentSelectorEmoji`);if(!n||!i)return;let o=e.find(e=>e.id===t)||e.find(e=>e.id==="default");if(o){let e=o.id==="default"?r(`agentMgr.defaultAgentName`):o.name;i.textContent=`${o.icon} ${e}`,a&&(a.textContent=o.icon),n.title=`${r(`header.switchAgent`)}: ${o.icon} ${e}`}else i.textContent=r(`header.defaultAssistant`),a&&(a.textContent=`🤖`),n.title=r(`header.switchAgent`)}function QT(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`),n=document.getElementById(`agentSelectorWrapper`);if(!e||!t||!n)return;let r=n.getBoundingClientRect(),i=document.body.clientWidth;t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,i-16)+`px`;let a=t.getBoundingClientRect().width,o=Math.min(a,i-16),s=e.getBoundingClientRect(),c=s.left+s.width/2,l=i-o-8,u=Math.max(8,Math.min(l,c-o/2));t.style.left=u-r.left+`px`}function $T(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`);!e||!t||(e.addEventListener(`click`,async e=>{if(e.stopPropagation(),t.style.display===`flex`)t.style.display=`none`;else{t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,document.body.clientWidth-16)+`px`,t.style.display=`flex`,QT();try{await XT()}catch{}QT()}}),document.addEventListener(`click`,()=>{t.style.display=`none`}),t.addEventListener(`click`,async e=>{let n=e.target.closest(`.agent-item`);if(!n)return;let r=e.target.closest(`[data-action]`);if(r&&r.dataset.action===`edit`){e.stopPropagation();let t=r.dataset.agentId;mE(t);return}if(r&&r.dataset.action===`delete`){e.stopPropagation(),await PE(r.dataset.agentId);return}if(n.id===`agentAddBtn`){mE(null);return}let i=n.dataset.agentId;i&&(await eE(i),t.style.display=`none`)}))}async function eE(e){let t=e?await ft(e):null;if(C.activeAgentId=e,C.activeAgentToolIds=t?t.toolIds:null,C.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null,await vt(e),ni().catch(()=>{}),t&&!t.isBuiltin)t.model&&(C.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(C.temperature=t.temperature,C.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`));else if(!t||t.isBuiltin)try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(C.currentModel=e.modelName),e.temperature!==void 0&&(C.temperature=e.temperature),e.topP!==void 0&&(C.topP=e.topP),document.dispatchEvent(new CustomEvent(`agent-model-changed`))}catch{}await XT();let n=`agentMcpClosedServers_${e||`default`}`,a=await chrome.storage.local.get([n,`ragTools`,`ragToolsIntroduced`]),o=a.ragTools||[];C.mcpClosedServers=a[n]||[];let s=`agentEnabledTools_${e||`default`}`,c=await chrome.storage.local.get([s,`enabledTools`]),l=!!c[s],u=c[s]||c.enabledTools;if(l||u&&u.length>0){let e=ta(o),t=u.filter(t=>e.has(t));if(l)C.enabledTools=t;else{let e=f.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);C.enabledTools=[...t,...e]}let n=ea(C.enabledTools,o,a.ragToolsIntroduced);C.enabledTools=n.tools,C.enabledTools.length!==u.length&&chrome.storage.local.set({[s]:C.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{C.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let e=ea(C.enabledTools,o,a.ragToolsIntroduced);C.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[s]:C.enabledTools})}let d=document.getElementById(`toolsPopupOverlay`);d&&d.classList.contains(`show`)&&(Bi(),Ji(),Yi()),Qi();let p=t&&t.id!=="default"?t.name:r(`agentMgr.defaultAgentName`);F(r(`agentMgr.switchedTo`,{name:p}),`info`,2e3),i.debug(`[AgentMgr] switched Agent:`,e,p)}function tE(){let e=document.getElementById(`agentEditModal`);if(!e)return;e.querySelector(`#agentModalCloseBtn`)?.addEventListener(`click`,hE),e.querySelector(`#agentSaveBtn`)?.addEventListener(`click`,ME),e.querySelector(`#agentDeleteBtn`)?.addEventListener(`click`,NE),e.querySelector(`#agentTemplateSelect`)?.addEventListener(`change`,_E),oE();let t=document.getElementById(`agentToolActions`);t&&t.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAll`?sE():n===`deselectAll`?cE():n===`toggleSelectedOnly`&&(vE.selectedOnly=!vE.selectedOnly,bE())});let n=document.getElementById(`agentToolSearchInput`);if(n){let e=null,t=document.getElementById(`agentToolSearchClear`),r=()=>{t&&(t.style.display=n.value?`block`:`none`)};n.addEventListener(`input`,()=>{r(),clearTimeout(e),e=setTimeout(()=>{vE.searchText=n.value,bE()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),n.value=``,r(),vE.searchText=``,bE(),n.focus()}),r()}let r=document.getElementById(`agentSkillActions`);r&&r.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAllSkills`?lE():n===`deselectAllSkills`?uE():n===`toggleSelectedOnlySkills`&&(wE.selectedOnly=!wE.selectedOnly,EE())});let i=document.getElementById(`agentSkillSearchInput`);if(i){let e=null,t=document.getElementById(`agentSkillSearchClear`),n=()=>{t&&(t.style.display=i.value?`block`:`none`)};i.addEventListener(`input`,()=>{n(),clearTimeout(e),e=setTimeout(()=>{wE.searchText=i.value,EE()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),i.value=``,n(),wE.searchText=``,EE(),i.focus()}),n()}let a=document.getElementById(`agentToolList`);a&&(a.addEventListener(`click`,e=>{let t=e.target.closest(`.agent-mcp-expand-btn`);if(t){e.preventDefault(),xE(t.dataset.serverId,t);return}let n=e.target.closest(`.agent-mcp-service-item`);if(n&&!e.target.closest(`input[type="checkbox"]`)){e.preventDefault(),xE(n.dataset.mcpServerId,n.querySelector(`.agent-mcp-expand-btn`));return}let r=e.target.closest(`.agent-tool-category-clickable`);r&&dE(r.dataset.category)}),a.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=vE,n=e.target.dataset.toolId,r=e.target.dataset.mcpServerId;t.inheritMode=!1,n?e.target.checked?t.selectedSet.add(n):t.selectedSet.delete(n):r&&(e.target.checked?t.excludedSet.delete(r):t.excludedSet.add(r)),t.selectedOnly?bE():fE()}));let o=document.getElementById(`agentSkillList`);o&&o.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=wE;t.inheritMode=!1,e.target.checked?t.selectedSet.add(e.target.value):t.selectedSet.delete(e.target.value),t.selectedOnly&&!e.target.checked?EE():pE()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`emojiPicker`),n=document.getElementById(`agentEditIconBtn`);t&&n&&t.style.display===`block`&&!n.contains(e.target)&&!t.contains(e.target)&&(t.style.display=`none`)})}var nE=[[`smileys`,`emojiCatSmileys`],[`people`,`emojiCatPeople`],[`animals`,`emojiCatAnimals`],[`food`,`emojiCatFood`],[`travel`,`emojiCatTravel`],[`activity`,`emojiCatActivity`],[`objects`,`emojiCatObjects`],[`symbols`,`emojiCatSymbols`],[`flags`,`emojiCatFlags`]];function rE(e,t){return!!(e[1].includes(t)||e[3]&&e[3].includes(t))}function iE(e){let t=``;for(let[e,n]of nE){let i=qT.filter(t=>t[2]===e);if(i.length){t+=`<div class="emoji-category-label">${r(`agentMgr.`+n)}</div>`,t+=`<div class="emoji-picker-grid">`;for(let e of i)t+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;t+=`</div>`}}e.innerHTML=t}function aE(e,t){let n=qT.filter(e=>rE(e,t));if(!n.length){e.innerHTML=`<div class="emoji-picker-empty">${r(`agentMgr.emojiNoMatch`)}</div>`;return}let i=`<div class="emoji-picker-grid">`;for(let e of n)i+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;i+=`</div>`,e.innerHTML=i}function oE(){let e=document.getElementById(`emojiPicker`),t=document.getElementById(`agentEditIconBtn`),n=document.getElementById(`agentEditIcon`),r=document.getElementById(`emojiSearchInput`),i=document.getElementById(`emojiSearchClear`),a=document.getElementById(`emojiPickerBody`);if(!e||!t)return;let o=()=>{let e=r?r.value.trim().toLowerCase():``;e?aE(a,e):iE(a),i&&(i.style.display=e?`flex`:`none`)};t.addEventListener(`click`,n=>{if(n.stopPropagation(),e.style.display===`block`){e.style.display=`none`;return}r&&(r.value=``),o();let i=t.getBoundingClientRect();document.body.clientWidth-i.left>=330?(e.style.left=`0`,e.style.right=`auto`):(e.style.left=`auto`,e.style.right=`0`),e.style.display=`block`}),r&&r.addEventListener(`input`,o),i&&i.addEventListener(`click`,e=>{e.stopPropagation(),r&&(r.value=``),o(),r&&r.focus()}),e.addEventListener(`click`,r=>{let i=r.target.closest(`.emoji-picker-item`);if(!i)return;let a=i.dataset.emoji;t.textContent=a,n&&(n.value=a),e.style.display=`none`})}function sE(){let e=vE;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.add(t.id)),e.mcpServices.forEach(t=>e.excludedSet.delete(t.serverId)),bE()}function cE(){let e=vE;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.delete(t.id)),e.mcpServices.forEach(t=>e.excludedSet.add(t.serverId)),bE()}function lE(){let e=wE;e.inheritMode=!1,e.skills.forEach(t=>e.selectedSet.add(t.name)),EE()}function uE(){let e=wE;e.inheritMode=!1,e.selectedSet.clear(),EE()}function dE(e){let t=vE;if(e===`mcp`){if(t.mcpServices.length===0)return;t.inheritMode=!1;let e=t.mcpServices.every(e=>!t.excludedSet.has(e.serverId));t.mcpServices.forEach(n=>{e?t.excludedSet.add(n.serverId):t.excludedSet.delete(n.serverId)}),document.querySelectorAll(`#agentToolList .agent-mcp-service-item input[type="checkbox"]`).forEach(t=>{t.checked=!e})}else{let n=t.allTools.filter(t=>(t.category||`other`)===e);if(n.length===0)return;t.inheritMode=!1;let r=n.every(e=>t.selectedSet.has(e.id));n.forEach(e=>{r?t.selectedSet.delete(e.id):t.selectedSet.add(e.id)}),document.querySelectorAll(`#agentToolList .agent-tool-item[data-category="${e}"] input[type="checkbox"]`).forEach(e=>{e.checked=!r})}t.selectedOnly?bE():fE()}function fE(){let e=vE,t=document.getElementById(`agentToolList`);if(!t)return;let n=e.mcpServices.filter(t=>!e.excludedSet.has(t.serverId)).length;t.querySelectorAll(`.agent-tool-category-clickable`).forEach(t=>{let r=t.dataset.category,i=t.querySelector(`.agent-tool-cat-count`);if(i)if(r===`mcp`)i.textContent=`${n}/${e.mcpServices.length}`;else{let t=e.allTools.filter(e=>(e.category||`other`)===r);i.textContent=`${t.filter(t=>e.selectedSet.has(t.id)).length}/${t.length}`}});let i=document.getElementById(`agentToolCount`);if(i){let t=e.allTools.filter(t=>e.selectedSet.has(t.id)).length,a=e.allTools.length+e.mcpServices.length;i.textContent=r(`agentConfig.selectedTotalCount`,{selected:e.inheritMode?a:t+n,total:a})}}function pE(){let e=document.getElementById(`agentSkillCount`);if(!e)return;let t=wE,n=t.skills.length;e.textContent=r(`agentConfig.selectedTotalCount`,{selected:t.inheritMode?n:t.selectedSet.size,total:n})}async function mE(e){let t=document.getElementById(`agentEditModal`);if(!t)return;await OE(),kE(-1),t.querySelector(`#agentEditId`).value=``,t.querySelector(`#agentEditName`).value=``,t.querySelector(`#agentEditIcon`).value=`🤖`;let n=t.querySelector(`#agentEditIconBtn`);n&&(n.textContent=`🤖`),t.querySelector(`#agentEditDesc`).value=``,t.querySelector(`#agentEditPrompt`).value=``,t.querySelector(`#agentEditAllowSub`).checked=!1,t.querySelector(`#agentTemplateSelect`).value=``,t.querySelector(`#agentEditModel`).value=``;let i=t.querySelector(`#agentDeleteBtn`),a=t.querySelector(`#agentEditTitle`);if(e){let n=await ft(e);if(!n||n.isBuiltin)return;a.textContent=r(`agentMgr.editAgent`),t.querySelector(`#agentEditId`).value=n.id,t.querySelector(`#agentEditName`).value=n.name,t.querySelector(`#agentEditIcon`).value=n.icon||`🤖`;let o=t.querySelector(`#agentEditIconBtn`);o&&(o.textContent=n.icon||`🤖`),t.querySelector(`#agentEditDesc`).value=n.description||``,t.querySelector(`#agentEditPrompt`).value=n.systemPrompt||``,t.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,t.querySelector(`#agentEditModel`).value=n.model||``,kE(jE(n.temperature,n.topP)),i.style.display=`block`,yE(n.toolIds,n.mcpExcludedServerIds??[]),TE(n.skillIds)}else a.textContent=r(`agentEditor.createNew`),i.style.display=`none`,yE(null,[]),TE(null);gE(),t.style.display=`flex`;let o=t.querySelector(`#agentEditModel`);if(o){let e=o.value,t=o.cloneNode(!0);o.parentNode.replaceChild(t,o),t.value=e,t.addEventListener(`mousedown`,()=>{let e=t.value;e&&(t.dataset._saved=e,t.value=``)}),t.addEventListener(`blur`,()=>{setTimeout(()=>{t.value||=t.dataset._saved||``},150)})}}function hE(){let e=document.getElementById(`agentEditModal`);e&&(e.style.display=`none`)}function gE(){let e=document.getElementById(`agentTemplateSelect`);if(!e)return;let t=[r(`agentTemplates.codeReviewName`),r(`agentTemplates.webAutomationName`),r(`agentTemplates.dataAnalystName`),r(`agentTemplates.documentationName`)],n=`<option value="">${r(`agentEditor.selectTemplate`)}</option>`;for(let e=0;e<_.length;e++){let r=_[e];n+=`<option value="${e}">${r.icon} ${t[e]}</option>`}e.innerHTML=n}function _E(e){let t=parseInt(e.target.value);if(isNaN(t)||t<0||t>=_.length)return;let n=_[t],i=document.getElementById(`agentEditModal`);if(!i)return;let o=[`agentTemplates.codeReviewName`,`agentTemplates.webAutomationName`,`agentTemplates.dataAnalystName`,`agentTemplates.documentationName`],s=[`agentTemplates.codeReviewDesc`,`agentTemplates.webAutomationDesc`,`agentTemplates.dataAnalystDesc`,`agentTemplates.documentationDesc`];i.querySelector(`#agentEditName`).value=r(o[t]),i.querySelector(`#agentEditIcon`).value=n.icon;let c=i.querySelector(`#agentEditIconBtn`);c&&(c.textContent=n.icon),i.querySelector(`#agentEditDesc`).value=r(s[t]),i.querySelector(`#agentEditPrompt`).value=a()===`en`?n.systemPrompt:n.systemPromptZh||n.systemPrompt,i.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,i.querySelector(`#agentEditModel`).value=n.model||``,kE(jE(n.temperature,n.topP)),yE(n.toolIds,[]),TE(n.skillIds||null),F(r(`agentMgr.templateLoaded`,{name:n.name}),`info`,2e3)}var vE={allTools:[],mcpServices:[],selectedSet:new Set,excludedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function yE(e,t){if(!document.getElementById(`agentToolList`))return;let n=[];try{n=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[]}catch{}let{mcpEnabled:r,skillsEnabled:i,ragTools:a}=await chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`ragTools`]),o=C.agentPlatform?.connected===!0,s=[...f,...a||[]];o||(s=s.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),i===!1&&(s=s.filter(e=>e.id!==`agent_skill`));let c=[];if(r===!0&&o){let e=new Map;for(let t of n){let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[]}),e.get(n).tools.push(t)}c=Array.from(e.values())}let l=new Set(Array.isArray(t)?t:[]),u=vE;u.allTools=s,u.mcpServices=c,u.selectedSet=new Set(e||[]),u.excludedSet=l,u.searchText=``,u.selectedOnly=!1,u.inheritMode=!e;let d=document.getElementById(`agentToolSearchInput`);d&&(d.value=``);let p=document.getElementById(`agentToolSearchClear`);p&&(p.style.display=`none`),bE()}function bE(){let e=document.getElementById(`agentToolList`);if(!e)return;let t=vE,n=aa({tools:t.allTools,services:t.mcpServices,selectedSet:t.selectedSet,excludedSet:t.excludedSet,query:t.searchText,selectedOnly:t.selectedOnly,getDesc:xi}),i=t.mcpServices.filter(e=>!t.excludedSet.has(e.serverId)).length,a={};for(let e of n.tools){let t=e.category||`other`;a[t]||(a[t]=[]),a[t].push(e)}let o=``;for(let[e,n]of Object.entries(a)){let i=r(`toolCategory.${e}`)===`toolCategory.${e}`?e:r(`toolCategory.${e}`),a=t.allTools.filter(t=>(t.category||`other`)===e),s=a.filter(e=>t.selectedSet.has(e.id)).length;o+=`<div class="agent-tool-category agent-tool-category-clickable" data-category="${$(e)}" title="${$(r(`agentConfig.toggleCategoryAll`))}">${i} <span class="agent-tool-cat-count" style="font-weight:400;color:var(--text-tertiary);">${s}/${a.length}</span></div>`;for(let r of n){let n=t.selectedSet.has(r.id)?`checked`:``,i=xi(r),a=i.length>40?i.substring(0,40)+`...`:i;o+=`
|
|
2090
|
+
</div>`),ZT(n,i)}function ZT(e,t){let n=document.getElementById(`agentSelectorBtn`),i=document.getElementById(`agentSelectorText`),a=document.getElementById(`agentSelectorEmoji`);if(!n||!i)return;let o=e.find(e=>e.id===t)||e.find(e=>e.id==="default");if(o){let e=o.id==="default"?r(`agentMgr.defaultAgentName`):o.name;i.textContent=`${o.icon} ${e}`,a&&(a.textContent=o.icon),n.title=`${r(`header.switchAgent`)}: ${o.icon} ${e}`}else i.textContent=r(`header.defaultAssistant`),a&&(a.textContent=`🤖`),n.title=r(`header.switchAgent`)}function QT(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`),n=document.getElementById(`agentSelectorWrapper`);if(!e||!t||!n)return;let r=n.getBoundingClientRect(),i=document.body.clientWidth;t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,i-16)+`px`;let a=t.getBoundingClientRect().width,o=Math.min(a,i-16),s=e.getBoundingClientRect(),c=s.left+s.width/2,l=i-o-8,u=Math.max(8,Math.min(l,c-o/2));t.style.left=u-r.left+`px`}function $T(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`);!e||!t||(e.addEventListener(`click`,async e=>{if(e.stopPropagation(),t.style.display===`flex`)t.style.display=`none`;else{t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,document.body.clientWidth-16)+`px`,t.style.display=`flex`,QT();try{await XT()}catch{}QT()}}),document.addEventListener(`click`,()=>{t.style.display=`none`}),t.addEventListener(`click`,async e=>{let n=e.target.closest(`.agent-item`);if(!n)return;let r=e.target.closest(`[data-action]`);if(r&&r.dataset.action===`edit`){e.stopPropagation();let t=r.dataset.agentId;mE(t);return}if(r&&r.dataset.action===`delete`){e.stopPropagation(),await PE(r.dataset.agentId);return}if(n.id===`agentAddBtn`){mE(null);return}let i=n.dataset.agentId;i&&(await eE(i),t.style.display=`none`)}))}async function eE(e){let t=e?await ft(e):null;if(C.activeAgentId=e,C.activeAgentToolIds=t?t.toolIds:null,C.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null,await vt(e),ni().catch(()=>{}),t&&!t.isBuiltin)t.model&&(C.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(C.temperature=t.temperature,C.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`));else if(!t||t.isBuiltin)try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(C.currentModel=e.modelName),e.temperature!==void 0&&(C.temperature=e.temperature),e.topP!==void 0&&(C.topP=e.topP),document.dispatchEvent(new CustomEvent(`agent-model-changed`))}catch{}await XT();let n=`agentMcpClosedServers_${e||`default`}`,a=await chrome.storage.local.get([n,`ragTools`,`ragToolsIntroduced`]),o=a.ragTools||[];C.mcpClosedServers=a[n]||[];let s=`agentEnabledTools_${e||`default`}`,c=await chrome.storage.local.get([s,`enabledTools`]),l=!!c[s],u=c[s]||c.enabledTools;if(l||u&&u.length>0){let e=ta(o),t=u.filter(t=>e.has(t));if(l)C.enabledTools=t;else{let e=f.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);C.enabledTools=[...t,...e]}let n=ea(C.enabledTools,o,a.ragToolsIntroduced);C.enabledTools=n.tools,C.enabledTools.length!==u.length&&chrome.storage.local.set({[s]:C.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{C.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let e=ea(C.enabledTools,o,a.ragToolsIntroduced);C.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[s]:C.enabledTools})}let d=document.getElementById(`toolsPopupOverlay`);d&&d.classList.contains(`show`)&&(Bi(),Ji(),Yi()),Qi();let p=t&&t.id!=="default"?t.name:r(`agentMgr.defaultAgentName`);P(r(`agentMgr.switchedTo`,{name:p}),`info`,2e3),i.debug(`[AgentMgr] switched Agent:`,e,p)}function tE(){let e=document.getElementById(`agentEditModal`);if(!e)return;e.querySelector(`#agentModalCloseBtn`)?.addEventListener(`click`,hE),e.querySelector(`#agentSaveBtn`)?.addEventListener(`click`,ME),e.querySelector(`#agentDeleteBtn`)?.addEventListener(`click`,NE),e.querySelector(`#agentTemplateSelect`)?.addEventListener(`change`,_E),oE();let t=document.getElementById(`agentToolActions`);t&&t.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAll`?sE():n===`deselectAll`?cE():n===`toggleSelectedOnly`&&(vE.selectedOnly=!vE.selectedOnly,bE())});let n=document.getElementById(`agentToolSearchInput`);if(n){let e=null,t=document.getElementById(`agentToolSearchClear`),r=()=>{t&&(t.style.display=n.value?`block`:`none`)};n.addEventListener(`input`,()=>{r(),clearTimeout(e),e=setTimeout(()=>{vE.searchText=n.value,bE()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),n.value=``,r(),vE.searchText=``,bE(),n.focus()}),r()}let r=document.getElementById(`agentSkillActions`);r&&r.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAllSkills`?lE():n===`deselectAllSkills`?uE():n===`toggleSelectedOnlySkills`&&(wE.selectedOnly=!wE.selectedOnly,EE())});let i=document.getElementById(`agentSkillSearchInput`);if(i){let e=null,t=document.getElementById(`agentSkillSearchClear`),n=()=>{t&&(t.style.display=i.value?`block`:`none`)};i.addEventListener(`input`,()=>{n(),clearTimeout(e),e=setTimeout(()=>{wE.searchText=i.value,EE()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),i.value=``,n(),wE.searchText=``,EE(),i.focus()}),n()}let a=document.getElementById(`agentToolList`);a&&(a.addEventListener(`click`,e=>{let t=e.target.closest(`.agent-mcp-expand-btn`);if(t){e.preventDefault(),xE(t.dataset.serverId,t);return}let n=e.target.closest(`.agent-mcp-service-item`);if(n&&!e.target.closest(`input[type="checkbox"]`)){e.preventDefault(),xE(n.dataset.mcpServerId,n.querySelector(`.agent-mcp-expand-btn`));return}let r=e.target.closest(`.agent-tool-category-clickable`);r&&dE(r.dataset.category)}),a.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=vE,n=e.target.dataset.toolId,r=e.target.dataset.mcpServerId;t.inheritMode=!1,n?e.target.checked?t.selectedSet.add(n):t.selectedSet.delete(n):r&&(e.target.checked?t.excludedSet.delete(r):t.excludedSet.add(r)),t.selectedOnly?bE():fE()}));let o=document.getElementById(`agentSkillList`);o&&o.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=wE;t.inheritMode=!1,e.target.checked?t.selectedSet.add(e.target.value):t.selectedSet.delete(e.target.value),t.selectedOnly&&!e.target.checked?EE():pE()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`emojiPicker`),n=document.getElementById(`agentEditIconBtn`);t&&n&&t.style.display===`block`&&!n.contains(e.target)&&!t.contains(e.target)&&(t.style.display=`none`)})}var nE=[[`smileys`,`emojiCatSmileys`],[`people`,`emojiCatPeople`],[`animals`,`emojiCatAnimals`],[`food`,`emojiCatFood`],[`travel`,`emojiCatTravel`],[`activity`,`emojiCatActivity`],[`objects`,`emojiCatObjects`],[`symbols`,`emojiCatSymbols`],[`flags`,`emojiCatFlags`]];function rE(e,t){return!!(e[1].includes(t)||e[3]&&e[3].includes(t))}function iE(e){let t=``;for(let[e,n]of nE){let i=qT.filter(t=>t[2]===e);if(i.length){t+=`<div class="emoji-category-label">${r(`agentMgr.`+n)}</div>`,t+=`<div class="emoji-picker-grid">`;for(let e of i)t+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;t+=`</div>`}}e.innerHTML=t}function aE(e,t){let n=qT.filter(e=>rE(e,t));if(!n.length){e.innerHTML=`<div class="emoji-picker-empty">${r(`agentMgr.emojiNoMatch`)}</div>`;return}let i=`<div class="emoji-picker-grid">`;for(let e of n)i+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;i+=`</div>`,e.innerHTML=i}function oE(){let e=document.getElementById(`emojiPicker`),t=document.getElementById(`agentEditIconBtn`),n=document.getElementById(`agentEditIcon`),r=document.getElementById(`emojiSearchInput`),i=document.getElementById(`emojiSearchClear`),a=document.getElementById(`emojiPickerBody`);if(!e||!t)return;let o=()=>{let e=r?r.value.trim().toLowerCase():``;e?aE(a,e):iE(a),i&&(i.style.display=e?`flex`:`none`)};t.addEventListener(`click`,n=>{if(n.stopPropagation(),e.style.display===`block`){e.style.display=`none`;return}r&&(r.value=``),o();let i=t.getBoundingClientRect();document.body.clientWidth-i.left>=330?(e.style.left=`0`,e.style.right=`auto`):(e.style.left=`auto`,e.style.right=`0`),e.style.display=`block`}),r&&r.addEventListener(`input`,o),i&&i.addEventListener(`click`,e=>{e.stopPropagation(),r&&(r.value=``),o(),r&&r.focus()}),e.addEventListener(`click`,r=>{let i=r.target.closest(`.emoji-picker-item`);if(!i)return;let a=i.dataset.emoji;t.textContent=a,n&&(n.value=a),e.style.display=`none`})}function sE(){let e=vE;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.add(t.id)),e.mcpServices.forEach(t=>e.excludedSet.delete(t.serverId)),bE()}function cE(){let e=vE;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.delete(t.id)),e.mcpServices.forEach(t=>e.excludedSet.add(t.serverId)),bE()}function lE(){let e=wE;e.inheritMode=!1,e.skills.forEach(t=>e.selectedSet.add(t.name)),EE()}function uE(){let e=wE;e.inheritMode=!1,e.selectedSet.clear(),EE()}function dE(e){let t=vE;if(e===`mcp`){if(t.mcpServices.length===0)return;t.inheritMode=!1;let e=t.mcpServices.every(e=>!t.excludedSet.has(e.serverId));t.mcpServices.forEach(n=>{e?t.excludedSet.add(n.serverId):t.excludedSet.delete(n.serverId)}),document.querySelectorAll(`#agentToolList .agent-mcp-service-item input[type="checkbox"]`).forEach(t=>{t.checked=!e})}else{let n=t.allTools.filter(t=>(t.category||`other`)===e);if(n.length===0)return;t.inheritMode=!1;let r=n.every(e=>t.selectedSet.has(e.id));n.forEach(e=>{r?t.selectedSet.delete(e.id):t.selectedSet.add(e.id)}),document.querySelectorAll(`#agentToolList .agent-tool-item[data-category="${e}"] input[type="checkbox"]`).forEach(e=>{e.checked=!r})}t.selectedOnly?bE():fE()}function fE(){let e=vE,t=document.getElementById(`agentToolList`);if(!t)return;let n=e.mcpServices.filter(t=>!e.excludedSet.has(t.serverId)).length;t.querySelectorAll(`.agent-tool-category-clickable`).forEach(t=>{let r=t.dataset.category,i=t.querySelector(`.agent-tool-cat-count`);if(i)if(r===`mcp`)i.textContent=`${n}/${e.mcpServices.length}`;else{let t=e.allTools.filter(e=>(e.category||`other`)===r);i.textContent=`${t.filter(t=>e.selectedSet.has(t.id)).length}/${t.length}`}});let i=document.getElementById(`agentToolCount`);if(i){let t=e.allTools.filter(t=>e.selectedSet.has(t.id)).length,a=e.allTools.length+e.mcpServices.length;i.textContent=r(`agentConfig.selectedTotalCount`,{selected:e.inheritMode?a:t+n,total:a})}}function pE(){let e=document.getElementById(`agentSkillCount`);if(!e)return;let t=wE,n=t.skills.length;e.textContent=r(`agentConfig.selectedTotalCount`,{selected:t.inheritMode?n:t.selectedSet.size,total:n})}async function mE(e){let t=document.getElementById(`agentEditModal`);if(!t)return;await OE(),kE(-1),t.querySelector(`#agentEditId`).value=``,t.querySelector(`#agentEditName`).value=``,t.querySelector(`#agentEditIcon`).value=`🤖`;let n=t.querySelector(`#agentEditIconBtn`);n&&(n.textContent=`🤖`),t.querySelector(`#agentEditDesc`).value=``,t.querySelector(`#agentEditPrompt`).value=``,t.querySelector(`#agentEditAllowSub`).checked=!1,t.querySelector(`#agentTemplateSelect`).value=``,t.querySelector(`#agentEditModel`).value=``;let i=t.querySelector(`#agentDeleteBtn`),a=t.querySelector(`#agentEditTitle`);if(e){let n=await ft(e);if(!n||n.isBuiltin)return;a.textContent=r(`agentMgr.editAgent`),t.querySelector(`#agentEditId`).value=n.id,t.querySelector(`#agentEditName`).value=n.name,t.querySelector(`#agentEditIcon`).value=n.icon||`🤖`;let o=t.querySelector(`#agentEditIconBtn`);o&&(o.textContent=n.icon||`🤖`),t.querySelector(`#agentEditDesc`).value=n.description||``,t.querySelector(`#agentEditPrompt`).value=n.systemPrompt||``,t.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,t.querySelector(`#agentEditModel`).value=n.model||``,kE(jE(n.temperature,n.topP)),i.style.display=`block`,yE(n.toolIds,n.mcpExcludedServerIds??[]),TE(n.skillIds)}else a.textContent=r(`agentEditor.createNew`),i.style.display=`none`,yE(null,[]),TE(null);gE(),t.style.display=`flex`;let o=t.querySelector(`#agentEditModel`);if(o){let e=o.value,t=o.cloneNode(!0);o.parentNode.replaceChild(t,o),t.value=e,t.addEventListener(`mousedown`,()=>{let e=t.value;e&&(t.dataset._saved=e,t.value=``)}),t.addEventListener(`blur`,()=>{setTimeout(()=>{t.value||=t.dataset._saved||``},150)})}}function hE(){let e=document.getElementById(`agentEditModal`);e&&(e.style.display=`none`)}function gE(){let e=document.getElementById(`agentTemplateSelect`);if(!e)return;let t=[r(`agentTemplates.codeReviewName`),r(`agentTemplates.webAutomationName`),r(`agentTemplates.dataAnalystName`),r(`agentTemplates.documentationName`)],n=`<option value="">${r(`agentEditor.selectTemplate`)}</option>`;for(let e=0;e<_.length;e++){let r=_[e];n+=`<option value="${e}">${r.icon} ${t[e]}</option>`}e.innerHTML=n}function _E(e){let t=parseInt(e.target.value);if(isNaN(t)||t<0||t>=_.length)return;let n=_[t],i=document.getElementById(`agentEditModal`);if(!i)return;let o=[`agentTemplates.codeReviewName`,`agentTemplates.webAutomationName`,`agentTemplates.dataAnalystName`,`agentTemplates.documentationName`],s=[`agentTemplates.codeReviewDesc`,`agentTemplates.webAutomationDesc`,`agentTemplates.dataAnalystDesc`,`agentTemplates.documentationDesc`];i.querySelector(`#agentEditName`).value=r(o[t]),i.querySelector(`#agentEditIcon`).value=n.icon;let c=i.querySelector(`#agentEditIconBtn`);c&&(c.textContent=n.icon),i.querySelector(`#agentEditDesc`).value=r(s[t]),i.querySelector(`#agentEditPrompt`).value=a()===`en`?n.systemPrompt:n.systemPromptZh||n.systemPrompt,i.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,i.querySelector(`#agentEditModel`).value=n.model||``,kE(jE(n.temperature,n.topP)),yE(n.toolIds,[]),TE(n.skillIds||null),P(r(`agentMgr.templateLoaded`,{name:n.name}),`info`,2e3)}var vE={allTools:[],mcpServices:[],selectedSet:new Set,excludedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function yE(e,t){if(!document.getElementById(`agentToolList`))return;let n=[];try{n=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[]}catch{}let{mcpEnabled:r,skillsEnabled:i,ragTools:a}=await chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`ragTools`]),o=C.agentPlatform?.connected===!0,s=[...f,...a||[]];o||(s=s.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),i===!1&&(s=s.filter(e=>e.id!==`agent_skill`));let c=[];if(r===!0&&o){let e=new Map;for(let t of n){let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[]}),e.get(n).tools.push(t)}c=Array.from(e.values())}let l=new Set(Array.isArray(t)?t:[]),u=vE;u.allTools=s,u.mcpServices=c,u.selectedSet=new Set(e||[]),u.excludedSet=l,u.searchText=``,u.selectedOnly=!1,u.inheritMode=!e;let d=document.getElementById(`agentToolSearchInput`);d&&(d.value=``);let p=document.getElementById(`agentToolSearchClear`);p&&(p.style.display=`none`),bE()}function bE(){let e=document.getElementById(`agentToolList`);if(!e)return;let t=vE,n=aa({tools:t.allTools,services:t.mcpServices,selectedSet:t.selectedSet,excludedSet:t.excludedSet,query:t.searchText,selectedOnly:t.selectedOnly,getDesc:xi}),i=t.mcpServices.filter(e=>!t.excludedSet.has(e.serverId)).length,a={};for(let e of n.tools){let t=e.category||`other`;a[t]||(a[t]=[]),a[t].push(e)}let o=``;for(let[e,n]of Object.entries(a)){let i=r(`toolCategory.${e}`)===`toolCategory.${e}`?e:r(`toolCategory.${e}`),a=t.allTools.filter(t=>(t.category||`other`)===e),s=a.filter(e=>t.selectedSet.has(e.id)).length;o+=`<div class="agent-tool-category agent-tool-category-clickable" data-category="${$(e)}" title="${$(r(`agentConfig.toggleCategoryAll`))}">${i} <span class="agent-tool-cat-count" style="font-weight:400;color:var(--text-tertiary);">${s}/${a.length}</span></div>`;for(let r of n){let n=t.selectedSet.has(r.id)?`checked`:``,i=xi(r),a=i.length>40?i.substring(0,40)+`...`:i;o+=`
|
|
2091
2091
|
<label class="agent-tool-item" data-category="${$(e)}">
|
|
2092
2092
|
<input type="checkbox" value="${$(r.id)}" ${n} data-tool-id="${$(r.id)}">
|
|
2093
2093
|
<span class="agent-tool-name" title="${$(r.name)}">${LE(r.name)}</span>
|
|
@@ -2105,7 +2105,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2105
2105
|
<input type="checkbox" value="${$(e.name)}" ${n}>
|
|
2106
2106
|
<span class="agent-tool-name" title="${$(e.name)}">${LE(e.name)}</span>
|
|
2107
2107
|
<span class="agent-tool-desc" title="${$(r)}">${LE(r.substring(0,40))}${r.length>40?`...`:``}</span>
|
|
2108
|
-
</label>`}).join(``)}let n=document.getElementById(`agentSkillSelectedOnlyBtn`);n&&(n.classList.toggle(`active`,t.selectedOnly),n.textContent=r(t.selectedOnly?`agentEditor.showAllSkills`:`agentEditor.selectedOnlyFilter`),n.title=r(`agentToolFilter.selectedCountHint`,{count:t.selectedSet.size})),pE()}function DE(){let e=wE,t=e.skills.filter(t=>e.selectedSet.has(t.name)).map(e=>e.name),n=new Set(t),r=[...e.selectedSet].filter(e=>!n.has(e)),i=[...t,...r];return i.length>0?i:null}async function OE(){let e=document.getElementById(`agentModelList`);if(e)return new Promise(t=>{chrome.storage.local.get([`customModels`],n=>{let r=[];(n.customModels||[]).forEach(e=>{let t;typeof e==`string`?t=e:e&&e.name&&(t=e.name),t&&!r.includes(t)&&r.push(t)}),e.innerHTML=r.map(e=>`<option value="${$(e)}">`).join(``),t()})})}function kE(e){let t=document.getElementById(`agentEditTempPreset`);if(t){for(;t.options.length>1;)t.remove(1);Qt.forEach((e,n)=>{let i=document.createElement(`option`);i.value=n,i.textContent=`${r(e.labelKey)}(${e.temp.toFixed(2)})`,t.appendChild(i)}),e!==void 0&&e>=0?t.value=e:t.value=``}}function AE(){let e=document.getElementById(`agentEditTempPreset`);if(!e||e.value===``)return{temperature:null,topP:null};let t=parseInt(e.value);if(isNaN(t)||t<0||t>=Qt.length)return{temperature:null,topP:null};let n=Qt[t];return{temperature:n.temp,topP:n.topP}}function jE(e,t){if(e==null)return-1;for(let n=0;n<Qt.length;n++){let r=Qt[n];if(Math.abs(r.temp-e)<.001&&Math.abs(r.topP-(t||1))<.001)return n}return-1}async function ME(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`).value,n=e.querySelector(`#agentEditName`).value.trim(),a=e.querySelector(`#agentEditIcon`).value.trim()||`🤖`,o=e.querySelector(`#agentEditDesc`).value.trim(),s=e.querySelector(`#agentEditPrompt`).value.trim(),c=e.querySelector(`#agentEditAllowSub`).checked,l=SE(),u=CE(),d=DE(),f=e.querySelector(`#agentEditModel`).value.trim()||null,{temperature:p,topP:m}=AE();if(!n){F(r(`agentMgr.nameRequired`),`warning`);return}let h={name:n,icon:a,description:o,systemPrompt:s,allowSubDispatch:c,toolIds:l,skillIds:d,model:f,temperature:p,topP:m};u!==void 0&&(h.mcpExcludedServerIds=u);try{t?(await pt(t,h),t===C.activeAgentId&&u!==void 0&&(C.activeAgentMcpExcludedServerIds=u),F(r(`agentMgr.agentUpdated`),`success`)):F(r(`agentMgr.agentCreated`,{name:(await ht(h)).name}),`success`),await YT(),await XT(),hE(),Qi()}catch(e){i.error(`[AgentMgr] save Agent failed:`,e),F(r(`agentMgr.saveFailed`,{message:e.message}),`error`)}}async function NE(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`)?.value;if(!t)return;let n=await ft(t);if(await RE(r(`agentMgr.confirmDeleteAgentMessage`,{name:n?n.name:``}),r(`agentMgr.deleteAgentTitle`)))try{await _t(t),F(r(`agentMgr.agentDeleted`),`success`),await YT(),await XT(),hE()}catch(e){i.error(`[AgentMgr] delete Agent failed:`,e),F(r(`agentMgr.deleteFailed`,{message:e.message}),`error`)}}async function PE(e){if(!e)return!1;let t=await ft(e);if(!t||t.isBuiltin)return F(r(`agentMgr.cannotDeleteDefault`),`warning`),!1;if(!await RE(r(`agentMgr.confirmDeleteAgentMessage`,{name:t.name}),r(`agentMgr.deleteAgentTitle`)))return!1;try{return await _t(e),F(r(`agentMgr.agentDeleted`),`success`),await YT(),await XT(),!0}catch(e){return i.error(`[AgentMgr] delete Agent failed:`,e),F(r(`agentMgr.deleteFailed`,{message:e.message}),`error`),!1}}async function FE(e=C.activeAgentId){return e?await ft(e):null}function IE(e){return e?e.toolIds:null}function LE(e){if(!e)return``;let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function $(e){return e?e.replace(/["&<>]/g,e=>({'"':`"`,"&":`&`,"<":`<`,">":`>`})[e]):``}async function RE(e,t){return typeof window.showCustomConfirm==`function`?window.showCustomConfirm(e,t):new Promise(n=>{let i=document.getElementById(`agentConfirmModal`);if(!i){n(confirm(e));return}i.querySelector(`#agentConfirmMessage`).textContent=e,i.querySelector(`#agentConfirmTitle`).textContent=t||r(`agentMgr.confirm`),i.style.display=`flex`;let a=()=>{i.style.display=`none`,i.querySelector(`#agentConfirmOk`).removeEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).removeEventListener(`click`,s),i.removeEventListener(`click`,c)},o=()=>{a(),n(!0)},s=()=>{a(),n(!1)},c=e=>{e.target===i&&(a(),n(!1))};i.querySelector(`#agentConfirmOk`).addEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).addEventListener(`click`,s),i.addEventListener(`click`,c)})}n(`zh`,{contextUsage:{indicatorTitle:`上下文占用 {percent}%({used} / {total} tokens)· 点击查看详情`,memoryOffToast:`记忆已关闭,无可压缩内容`,generatingToast:`正在生成回复,请稍后再试`,nothingToCompactToast:`没有新的消息可压缩`,confirmTitle:`压缩上下文`,confirmMessage:`将压缩 {count} 条历史消息(约 {tokens} tokens)为一份摘要{summaryHint}。原始消息仍保留在会话中,发送新消息前可撤销。`,confirmWithOldSummary:`(含已有摘要,将合并为新摘要)`,confirmOk:`开始压缩`,compactingTitle:`正在压缩上下文`,compactingHint:`正在调用模型生成摘要,请稍候…(通常需要几秒到十几秒)`,compactDone:`压缩完成,节约约 {saved} tokens`,compactErrConfig:`无法压缩:API 配置缺失`,compactErrFailed:`压缩失败,请稍后重试`,compactErrEmpty:`模型未返回摘要内容`,compactErrHttp:`接口错误 HTTP {status}`,compactErrTimeout:`请求超时`,autoCompactedToast:`上下文接近上限,已自动压缩(预计省 {saved} tokens)`,undoTitle:`撤销压缩`,undoMessage:`撤销后,发送将恢复携带完整历史。确定撤销吗?`,undoOk:`撤销`,undoDone:`已撤销压缩`,dividerText:`⬆ 上方 {count} 条消息已压缩为摘要`,dividerView:`查看`,dividerUndo:`撤销`,popupTitle:`上下文占用明细`,rowSystem:`系统提示词`,rowTools:`工具定义`,rowHistory:`历史消息`,rowInput:`当前输入`,historyMeta:`选中 {selected} 条 / 共 {total} 条`,historyTrimmed:`为控制预算裁剪了 {count} 条(以规则摘要替代)`,refInfo:`输出预留 {output} · 安全余量 {safety}(不计入上方占用)`,memoryLabel:`记忆设置`,memoryAll:`携带全部历史`,memoryLimited:`携带最近 {n} 条`,memoryOff:`不携带历史(仅当前消息)`,compactionActive:`已压缩 {count} 条历史 · 摘要约 {tokens} tokens`,compactionInvalidHint:`压缩点已失效(对应消息已被删除),本次发送未使用压缩`,removeInvalid:`移除失效的压缩记录`,btnCompact:`压缩上下文`,btnCompactAgain:`再次压缩`,btnUndoCompact:`撤销压缩`,undoExpiredToast:`已发送新消息,无法再撤销压缩(可再次压缩合并更新)`,summaryTitle:`上下文摘要(压缩 {count} 条历史)`,summaryTabPreview:`预览`,summaryTabSource:`源码`}}),n(`en`,{contextUsage:{indicatorTitle:`Context usage {percent}% ({used} / {total} tokens) · Click for details`,memoryOffToast:`Memory is off, nothing to compact`,generatingToast:`Generating a reply, please try again later`,nothingToCompactToast:`No new messages to compact`,confirmTitle:`Compact Context`,confirmMessage:`Compact {count} history messages (~{tokens} tokens) into a summary{summaryHint}. Original messages remain in the session; undo is available before sending new messages.`,confirmWithOldSummary:` (including the existing summary, which will be merged into a new one)`,confirmOk:`Start Compaction`,compactingTitle:`Compacting Context`,compactingHint:`Generating a summary with the model, please wait… (usually takes a few seconds)`,compactDone:`Compaction complete, saved ~{saved} tokens`,compactErrConfig:`Cannot compact: API configuration missing`,compactErrFailed:`Compaction failed, please try again later`,compactErrEmpty:`the model returned no summary`,compactErrHttp:`API error HTTP {status}`,compactErrTimeout:`request timed out`,autoCompactedToast:`Context is near its limit; auto-compacted (est. {saved} tokens saved)`,undoTitle:`Undo Compaction`,undoMessage:`After undo, sending will include the full history again. Undo?`,undoOk:`Undo`,undoDone:`Compaction undone`,dividerText:`⬆ {count} messages above compacted into a summary`,dividerView:`View`,dividerUndo:`Undo`,popupTitle:`Context Usage Details`,rowSystem:`System prompt`,rowTools:`Tool definitions`,rowHistory:`History messages`,rowInput:`Current input`,historyMeta:`Selected {selected} / {total} total`,historyTrimmed:`{count} messages trimmed for budget (replaced by rule summary)`,refInfo:`Output reserve {output} · Safety margin {safety} (not counted above)`,memoryLabel:`Memory setting`,memoryAll:`Carry all history`,memoryLimited:`Carry latest {n} messages`,memoryOff:`No history (current message only)`,compactionActive:`{count} messages compacted · summary ~{tokens} tokens`,compactionInvalidHint:`Compaction point is stale (its message was deleted); this send ignores the compaction`,removeInvalid:`Remove stale compaction record`,btnCompact:`Compact Context`,btnCompactAgain:`Compact Again`,btnUndoCompact:`Undo Compaction`,undoExpiredToast:`New messages have been sent; compaction can no longer be undone (you can compact again)`,summaryTitle:`Context Summary ({count} messages compacted)`,summaryTabPreview:`Preview`,summaryTabSource:`Source`}});var zE=300,BE=``,VE=0,HE=null;async function UE(){try{let{mcpTools:e}=await chrome.storage.local.get([`mcpTools`]),t=e||[],n=new Set(Array.isArray(C.mcpClosedServers)?C.mcpClosedServers:[]),r=new Set(Array.isArray(C.activeAgentMcpExcludedServerIds)?C.activeAgentMcpExcludedServerIds:[]);return t.filter(e=>{let t=e.serverId||`unknown`;return!n.has(t)&&!r.has(t)}).length}catch{return 0}}function WE(){let e=document.getElementById(`userInput`)?.value||``;return{usage:on({model:C.currentModel,customModelMap:C.customModelMap,systemPromptText:BE,toolCount:(C.useTools?C.enabledTools.length:0)+VE,history:C.messageHistory,inputText:e,maxMemoryMessages:C.chatConfig?.maxMemoryMessages??null,compaction:C.activeCompaction,isolateChat:C.isolateChat}),inputText:e}}function GE(e){let t=document.getElementById(`contextUsageIndicator`);if(!t)return;t._lastUsage=e,t.dataset.level=e.level;let n=Math.round(e.ratio*100),i=t.querySelector(`.context-usage-percent`);i&&(i.textContent=`${n}%`),t.style.setProperty(`--usage-ratio`,String(Math.min(Math.max(e.ratio,0),1))),t.title=r(`contextUsage.indicatorTitle`,{percent:n,used:I(e.usedTokens),total:I(e.contextWindow)})}function KE(){try{let{usage:e}=WE();return GE(e),iD(),e}catch(e){return i.warn(`[ContextIndicator] update failed:`,e?.message),null}}function qE(){clearTimeout(HE),HE=setTimeout(()=>KE(),zE)}async function JE(e=null){let t=e===null?C.activeSessionId:e;try{BE=await Ke(await FE(),{sessionId:t})}catch(e){i.warn(`[ContextIndicator] refresh system prompt failed:`,e?.message)}try{VE=await UE()}catch{VE=0}KE()}function YE(){let e=document.getElementById(`contextUsageIndicator`);e&&(e.addEventListener(`click`,()=>cD()),document.getElementById(`userInput`)?.addEventListener(`input`,qE),document.addEventListener(`generating-state-changed`,()=>{JE()}),document.addEventListener(`agent-model-changed`,()=>{JE()}),document.addEventListener(`session-switched`,()=>{JE()}),document.addEventListener(`session-workdir-changed`,()=>{JE()}),chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&((e.chatMaxMemoryMessages||e.isolateChat)&&qE(),(e.modelName||e.customModels)&&qE(),(e.isolateChat||e.mcpTools||e.mcpEnabled||e.enabledTools||e.enableTools)&&JE())}),JE())}function XE({title:e,message:t,okText:n}){return new Promise(i=>{let a=document.createElement(`div`);a.className=`modal-overlay show`,a.style.zIndex=`10200`,a.innerHTML=`
|
|
2108
|
+
</label>`}).join(``)}let n=document.getElementById(`agentSkillSelectedOnlyBtn`);n&&(n.classList.toggle(`active`,t.selectedOnly),n.textContent=r(t.selectedOnly?`agentEditor.showAllSkills`:`agentEditor.selectedOnlyFilter`),n.title=r(`agentToolFilter.selectedCountHint`,{count:t.selectedSet.size})),pE()}function DE(){let e=wE,t=e.skills.filter(t=>e.selectedSet.has(t.name)).map(e=>e.name),n=new Set(t),r=[...e.selectedSet].filter(e=>!n.has(e)),i=[...t,...r];return i.length>0?i:null}async function OE(){let e=document.getElementById(`agentModelList`);if(e)return new Promise(t=>{chrome.storage.local.get([`customModels`],n=>{let r=[];(n.customModels||[]).forEach(e=>{let t;typeof e==`string`?t=e:e&&e.name&&(t=e.name),t&&!r.includes(t)&&r.push(t)}),e.innerHTML=r.map(e=>`<option value="${$(e)}">`).join(``),t()})})}function kE(e){let t=document.getElementById(`agentEditTempPreset`);if(t){for(;t.options.length>1;)t.remove(1);Qt.forEach((e,n)=>{let i=document.createElement(`option`);i.value=n,i.textContent=`${r(e.labelKey)}(${e.temp.toFixed(2)})`,t.appendChild(i)}),e!==void 0&&e>=0?t.value=e:t.value=``}}function AE(){let e=document.getElementById(`agentEditTempPreset`);if(!e||e.value===``)return{temperature:null,topP:null};let t=parseInt(e.value);if(isNaN(t)||t<0||t>=Qt.length)return{temperature:null,topP:null};let n=Qt[t];return{temperature:n.temp,topP:n.topP}}function jE(e,t){if(e==null)return-1;for(let n=0;n<Qt.length;n++){let r=Qt[n];if(Math.abs(r.temp-e)<.001&&Math.abs(r.topP-(t||1))<.001)return n}return-1}async function ME(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`).value,n=e.querySelector(`#agentEditName`).value.trim(),a=e.querySelector(`#agentEditIcon`).value.trim()||`🤖`,o=e.querySelector(`#agentEditDesc`).value.trim(),s=e.querySelector(`#agentEditPrompt`).value.trim(),c=e.querySelector(`#agentEditAllowSub`).checked,l=SE(),u=CE(),d=DE(),f=e.querySelector(`#agentEditModel`).value.trim()||null,{temperature:p,topP:m}=AE();if(!n){P(r(`agentMgr.nameRequired`),`warning`);return}let h={name:n,icon:a,description:o,systemPrompt:s,allowSubDispatch:c,toolIds:l,skillIds:d,model:f,temperature:p,topP:m};u!==void 0&&(h.mcpExcludedServerIds=u);try{t?(await pt(t,h),t===C.activeAgentId&&u!==void 0&&(C.activeAgentMcpExcludedServerIds=u),P(r(`agentMgr.agentUpdated`),`success`)):P(r(`agentMgr.agentCreated`,{name:(await ht(h)).name}),`success`),await YT(),await XT(),hE(),Qi()}catch(e){i.error(`[AgentMgr] save Agent failed:`,e),P(r(`agentMgr.saveFailed`,{message:e.message}),`error`)}}async function NE(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`)?.value;if(!t)return;let n=await ft(t);if(await RE(r(`agentMgr.confirmDeleteAgentMessage`,{name:n?n.name:``}),r(`agentMgr.deleteAgentTitle`)))try{await _t(t),P(r(`agentMgr.agentDeleted`),`success`),await YT(),await XT(),hE()}catch(e){i.error(`[AgentMgr] delete Agent failed:`,e),P(r(`agentMgr.deleteFailed`,{message:e.message}),`error`)}}async function PE(e){if(!e)return!1;let t=await ft(e);if(!t||t.isBuiltin)return P(r(`agentMgr.cannotDeleteDefault`),`warning`),!1;if(!await RE(r(`agentMgr.confirmDeleteAgentMessage`,{name:t.name}),r(`agentMgr.deleteAgentTitle`)))return!1;try{return await _t(e),P(r(`agentMgr.agentDeleted`),`success`),await YT(),await XT(),!0}catch(e){return i.error(`[AgentMgr] delete Agent failed:`,e),P(r(`agentMgr.deleteFailed`,{message:e.message}),`error`),!1}}async function FE(e=C.activeAgentId){return e?await ft(e):null}function IE(e){return e?e.toolIds:null}function LE(e){if(!e)return``;let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function $(e){return e?e.replace(/["&<>]/g,e=>({'"':`"`,"&":`&`,"<":`<`,">":`>`})[e]):``}async function RE(e,t){return typeof window.showCustomConfirm==`function`?window.showCustomConfirm(e,t):new Promise(n=>{let i=document.getElementById(`agentConfirmModal`);if(!i){n(confirm(e));return}i.querySelector(`#agentConfirmMessage`).textContent=e,i.querySelector(`#agentConfirmTitle`).textContent=t||r(`agentMgr.confirm`),i.style.display=`flex`;let a=()=>{i.style.display=`none`,i.querySelector(`#agentConfirmOk`).removeEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).removeEventListener(`click`,s),i.removeEventListener(`click`,c)},o=()=>{a(),n(!0)},s=()=>{a(),n(!1)},c=e=>{e.target===i&&(a(),n(!1))};i.querySelector(`#agentConfirmOk`).addEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).addEventListener(`click`,s),i.addEventListener(`click`,c)})}n(`zh`,{contextUsage:{indicatorTitle:`上下文占用 {percent}%({used} / {total} tokens)· 点击查看详情`,memoryOffToast:`记忆已关闭,无可压缩内容`,generatingToast:`正在生成回复,请稍后再试`,nothingToCompactToast:`没有新的消息可压缩`,confirmTitle:`压缩上下文`,confirmMessage:`将压缩 {count} 条历史消息(约 {tokens} tokens)为一份摘要{summaryHint}。原始消息仍保留在会话中,发送新消息前可撤销。`,confirmWithOldSummary:`(含已有摘要,将合并为新摘要)`,confirmOk:`开始压缩`,compactingTitle:`正在压缩上下文`,compactingHint:`正在调用模型生成摘要,请稍候…(通常需要几秒到十几秒)`,compactDone:`压缩完成,节约约 {saved} tokens`,compactErrConfig:`无法压缩:API 配置缺失`,compactErrFailed:`压缩失败,请稍后重试`,compactErrEmpty:`模型未返回摘要内容`,compactErrHttp:`接口错误 HTTP {status}`,compactErrTimeout:`请求超时`,autoCompactedToast:`上下文接近上限,已自动压缩(预计省 {saved} tokens)`,undoTitle:`撤销压缩`,undoMessage:`撤销后,发送将恢复携带完整历史。确定撤销吗?`,undoOk:`撤销`,undoDone:`已撤销压缩`,dividerText:`⬆ 上方 {count} 条消息已压缩为摘要`,dividerView:`查看`,dividerUndo:`撤销`,popupTitle:`上下文占用明细`,rowSystem:`系统提示词`,rowTools:`工具定义`,rowHistory:`历史消息`,rowInput:`当前输入`,historyMeta:`选中 {selected} 条 / 共 {total} 条`,historyTrimmed:`为控制预算裁剪了 {count} 条(以规则摘要替代)`,refInfo:`输出预留 {output} · 安全余量 {safety}(不计入上方占用)`,memoryLabel:`记忆设置`,memoryAll:`携带全部历史`,memoryLimited:`携带最近 {n} 条`,memoryOff:`不携带历史(仅当前消息)`,compactionActive:`已压缩 {count} 条历史 · 摘要约 {tokens} tokens`,compactionInvalidHint:`压缩点已失效(对应消息已被删除),本次发送未使用压缩`,removeInvalid:`移除失效的压缩记录`,btnCompact:`压缩上下文`,btnCompactAgain:`再次压缩`,btnUndoCompact:`撤销压缩`,undoExpiredToast:`已发送新消息,无法再撤销压缩(可再次压缩合并更新)`,summaryTitle:`上下文摘要(压缩 {count} 条历史)`,summaryTabPreview:`预览`,summaryTabSource:`源码`}}),n(`en`,{contextUsage:{indicatorTitle:`Context usage {percent}% ({used} / {total} tokens) · Click for details`,memoryOffToast:`Memory is off, nothing to compact`,generatingToast:`Generating a reply, please try again later`,nothingToCompactToast:`No new messages to compact`,confirmTitle:`Compact Context`,confirmMessage:`Compact {count} history messages (~{tokens} tokens) into a summary{summaryHint}. Original messages remain in the session; undo is available before sending new messages.`,confirmWithOldSummary:` (including the existing summary, which will be merged into a new one)`,confirmOk:`Start Compaction`,compactingTitle:`Compacting Context`,compactingHint:`Generating a summary with the model, please wait… (usually takes a few seconds)`,compactDone:`Compaction complete, saved ~{saved} tokens`,compactErrConfig:`Cannot compact: API configuration missing`,compactErrFailed:`Compaction failed, please try again later`,compactErrEmpty:`the model returned no summary`,compactErrHttp:`API error HTTP {status}`,compactErrTimeout:`request timed out`,autoCompactedToast:`Context is near its limit; auto-compacted (est. {saved} tokens saved)`,undoTitle:`Undo Compaction`,undoMessage:`After undo, sending will include the full history again. Undo?`,undoOk:`Undo`,undoDone:`Compaction undone`,dividerText:`⬆ {count} messages above compacted into a summary`,dividerView:`View`,dividerUndo:`Undo`,popupTitle:`Context Usage Details`,rowSystem:`System prompt`,rowTools:`Tool definitions`,rowHistory:`History messages`,rowInput:`Current input`,historyMeta:`Selected {selected} / {total} total`,historyTrimmed:`{count} messages trimmed for budget (replaced by rule summary)`,refInfo:`Output reserve {output} · Safety margin {safety} (not counted above)`,memoryLabel:`Memory setting`,memoryAll:`Carry all history`,memoryLimited:`Carry latest {n} messages`,memoryOff:`No history (current message only)`,compactionActive:`{count} messages compacted · summary ~{tokens} tokens`,compactionInvalidHint:`Compaction point is stale (its message was deleted); this send ignores the compaction`,removeInvalid:`Remove stale compaction record`,btnCompact:`Compact Context`,btnCompactAgain:`Compact Again`,btnUndoCompact:`Undo Compaction`,undoExpiredToast:`New messages have been sent; compaction can no longer be undone (you can compact again)`,summaryTitle:`Context Summary ({count} messages compacted)`,summaryTabPreview:`Preview`,summaryTabSource:`Source`}});var zE=300,BE=``,VE=0,HE=null;async function UE(){try{let{mcpTools:e}=await chrome.storage.local.get([`mcpTools`]),t=e||[],n=new Set(Array.isArray(C.mcpClosedServers)?C.mcpClosedServers:[]),r=new Set(Array.isArray(C.activeAgentMcpExcludedServerIds)?C.activeAgentMcpExcludedServerIds:[]);return t.filter(e=>{let t=e.serverId||`unknown`;return!n.has(t)&&!r.has(t)}).length}catch{return 0}}function WE(){let e=document.getElementById(`userInput`)?.value||``;return{usage:on({model:C.currentModel,customModelMap:C.customModelMap,systemPromptText:BE,toolCount:(C.useTools?C.enabledTools.length:0)+VE,history:C.messageHistory,inputText:e,maxMemoryMessages:C.chatConfig?.maxMemoryMessages??null,compaction:C.activeCompaction,isolateChat:C.isolateChat}),inputText:e}}function GE(e){let t=document.getElementById(`contextUsageIndicator`);if(!t)return;t._lastUsage=e,t.dataset.level=e.level;let n=Math.round(e.ratio*100),i=t.querySelector(`.context-usage-percent`);i&&(i.textContent=`${n}%`),t.style.setProperty(`--usage-ratio`,String(Math.min(Math.max(e.ratio,0),1))),t.title=r(`contextUsage.indicatorTitle`,{percent:n,used:F(e.usedTokens),total:F(e.contextWindow)})}function KE(){try{let{usage:e}=WE();return GE(e),iD(),e}catch(e){return i.warn(`[ContextIndicator] update failed:`,e?.message),null}}function qE(){clearTimeout(HE),HE=setTimeout(()=>KE(),zE)}async function JE(e=null){let t=e===null?C.activeSessionId:e;try{BE=await Ge(await FE(),{sessionId:t})}catch(e){i.warn(`[ContextIndicator] refresh system prompt failed:`,e?.message)}try{VE=await UE()}catch{VE=0}KE()}function YE(){let e=document.getElementById(`contextUsageIndicator`);e&&(e.addEventListener(`click`,()=>cD()),document.getElementById(`userInput`)?.addEventListener(`input`,qE),document.addEventListener(`generating-state-changed`,()=>{JE()}),document.addEventListener(`agent-model-changed`,()=>{JE()}),document.addEventListener(`session-switched`,()=>{JE()}),document.addEventListener(`session-workdir-changed`,()=>{JE()}),chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&((e.chatMaxMemoryMessages||e.isolateChat)&&qE(),(e.modelName||e.customModels)&&qE(),(e.isolateChat||e.mcpTools||e.mcpEnabled||e.enabledTools||e.enableTools)&&JE())}),JE())}function XE({title:e,message:t,okText:n}){return new Promise(i=>{let a=document.createElement(`div`);a.className=`modal-overlay show`,a.style.zIndex=`10200`,a.innerHTML=`
|
|
2109
2109
|
<div class="modal-container">
|
|
2110
2110
|
<div class="modal-title"></div>
|
|
2111
2111
|
<div class="modal-message"></div>
|
|
@@ -2119,13 +2119,13 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2119
2119
|
<div class="modal-title"></div>
|
|
2120
2120
|
<div class="modal-message"></div>
|
|
2121
2121
|
</div>
|
|
2122
|
-
`,e.querySelector(`.modal-title`).textContent=r(`contextUsage.compactingTitle`),e.querySelector(`.modal-message`).textContent=r(`contextUsage.compactingHint`),document.body.appendChild(e),{close:()=>e.remove()}}function QE(e){let t=String(e||``);if(t===`empty_summary`)return r(`contextUsage.compactErrEmpty`);if(t.includes(`CHAT_STREAM_IDLE_TIMEOUT`))return r(`contextUsage.compactErrTimeout`);if(t.startsWith(`http_`)){let e=t.slice(5),n=e.indexOf(`:`),i=r(`contextUsage.compactErrHttp`,{status:n<0?e:e.slice(0,n)}),a=n<0?``:e.slice(n+1).trim();if(!a)return i;let o=a;try{let e=JSON.parse(a);o=e?.error?.message||e?.message||a}catch{}return`${i}: ${String(o).slice(0,200)}`}return t.includes(`超时`)||/timeout/i.test(t)?r(`contextUsage.compactErrTimeout`):t}async function $E({silent:e=!1}={}){if(!C.isolateChat)return e||
|
|
2122
|
+
`,e.querySelector(`.modal-title`).textContent=r(`contextUsage.compactingTitle`),e.querySelector(`.modal-message`).textContent=r(`contextUsage.compactingHint`),document.body.appendChild(e),{close:()=>e.remove()}}function QE(e){let t=String(e||``);if(t===`empty_summary`)return r(`contextUsage.compactErrEmpty`);if(t.includes(`CHAT_STREAM_IDLE_TIMEOUT`))return r(`contextUsage.compactErrTimeout`);if(t.startsWith(`http_`)){let e=t.slice(5),n=e.indexOf(`:`),i=r(`contextUsage.compactErrHttp`,{status:n<0?e:e.slice(0,n)}),a=n<0?``:e.slice(n+1).trim();if(!a)return i;let o=a;try{let e=JSON.parse(a);o=e?.error?.message||e?.message||a}catch{}return`${i}: ${String(o).slice(0,200)}`}return t.includes(`超时`)||/timeout/i.test(t)?r(`contextUsage.compactErrTimeout`):t}async function $E({silent:e=!1}={}){if(!C.isolateChat)return e||P(r(`contextUsage.memoryOffToast`),`warning`),{success:!1,reason:`memory_off`};if(C.isGenerating)return e||P(r(`contextUsage.generatingToast`),`warning`),{success:!1,reason:`generating`};let t=C.messageHistory;if(!t.length)return e||P(r(`contextUsage.nothingToCompactToast`),`warning`),{success:!1,reason:`nothing_to_compact`};let n=C.activeCompaction,{material:a,includedCount:o,hasOldSummary:c}=sn(t,{maxMemoryMessages:C.chatConfig?.maxMemoryMessages??null,compaction:n});if(o===0)return e||P(r(`contextUsage.nothingToCompactToast`),`warning`),{success:!1,reason:`nothing_to_compact`};let l=E(a.map(e=>({role:e.role,content:e.content})));if(!e&&!await XE({title:r(`contextUsage.confirmTitle`),message:r(`contextUsage.confirmMessage`,{count:o,tokens:F(l),summaryHint:c?r(`contextUsage.confirmWithOldSummary`):``}),okText:r(`contextUsage.confirmOk`)}))return{success:!1,reason:`cancelled`};let u=e?null:ZE();try{let i=await chrome.runtime.sendMessage({type:`COMPACT_CONTEXT_SUMMARY`,material:a,model:C.currentModel,sessionId:C.activeSessionId,persistSummaryToMemory:C.chatConfig?.persistSummaryToMemory!==!1,compressedCount:(n?.compressedCount||0)+o,revision:(n?.revision||0)+1,memoryId:n?.memoryId||null});if(!i?.success||!i.summary){if(!e)if(i?.error===`config_missing`)P(r(`contextUsage.compactErrConfig`),`error`);else{let e=QE(i?.error);P(`${r(`contextUsage.compactErrFailed`)}${e?`(${e})`:``}`,`error`)}return{success:!1,reason:i?.error||`failed`}}let c=t[t.length-1],u=s(i.summary);return C.activeCompaction={summary:i.summary,upToMessageId:c?.messageId,compressedCount:(n?.compressedCount||0)+o,summaryTokens:u,savedTokens:Math.max(l-u,0),model:C.currentModel,createdAt:Date.now(),revision:(n?.revision||0)+1,memoryId:i.memoryId||n?.memoryId||null},await ni(),aD(),KE(),Yc(),e?P(r(`contextUsage.autoCompactedToast`,{saved:F(C.activeCompaction.savedTokens)}),`info`):P(r(`contextUsage.compactDone`,{saved:F(C.activeCompaction.savedTokens)}),`success`),{success:!0,savedTokens:C.activeCompaction.savedTokens}}catch(t){if(i.warn(`[ContextIndicator] compaction failed:`,t?.message),!e){let e=QE(t?.message);P(`${r(`contextUsage.compactErrFailed`)}${e?`(${e})`:``}`,`error`)}return{success:!1,reason:`exception`}}finally{u?.close()}}async function eD(){await $E({silent:!1})}function tD(){let e=C.activeCompaction;if(!e?.upToMessageId)return!1;let t=C.messageHistory||[],n=t.findIndex(t=>t.messageId===e.upToMessageId);return n>=0&&n<t.length-1}async function nD(e=!1){if(C.activeCompaction){if(tD()){P(r(`contextUsage.undoExpiredToast`),`warning`);return}!e&&!await XE({title:r(`contextUsage.undoTitle`),message:r(`contextUsage.undoMessage`),okText:r(`contextUsage.undoOk`)})||(C.activeCompaction=null,await ni(),rD(),KE(),P(r(`contextUsage.undoDone`),`success`))}}function rD(){document.querySelectorAll(`.compaction-divider`).forEach(e=>e.remove())}function iD(){let e=tD();document.querySelectorAll(`.compaction-divider [data-action="undo"]`).forEach(t=>{t.style.display=e?`none`:``})}function aD(){rD();let e=C.activeCompaction;if(!e?.upToMessageId)return;let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.querySelector(`[data-message-id="${CSS.escape(e.upToMessageId)}"]`);if(!n)return;let i=document.createElement(`div`);i.className=`compaction-divider`;let a=!tD();i.innerHTML=`
|
|
2123
2123
|
<span class="compaction-divider-text">${r(`contextUsage.dividerText`,{count:e.compressedCount})}</span>
|
|
2124
2124
|
<button class="compaction-divider-btn" data-action="view">${r(`contextUsage.dividerView`)}</button>
|
|
2125
2125
|
${a?`<button class="compaction-divider-btn" data-action="undo">${r(`contextUsage.dividerUndo`)}</button>`:``}
|
|
2126
2126
|
`,i.querySelector(`[data-action="view"]`).addEventListener(`click`,()=>lD(e)),i.querySelector(`[data-action="undo"]`)?.addEventListener(`click`,()=>nD()),n.after(i)}var oD=null;function sD(){document.querySelectorAll(`.context-usage-popup`).forEach(e=>e.remove());let e=document.getElementById(`contextUsageIndicator`);e&&(e._ctxPopupOpen=!1),oD&&=(document.removeEventListener(`click`,oD),null)}function cD(){let e=document.getElementById(`contextUsageIndicator`);if(!e)return;if(e._ctxPopupOpen){sD();return}sD(),e._ctxPopupOpen=!0;let{usage:t}=WE(),n=t.breakdown,i=Math.round(t.ratio*100),a;a=C.isolateChat?C.chatConfig?.maxMemoryMessages>0?r(`contextUsage.memoryLimited`,{n:C.chatConfig.maxMemoryMessages}):r(`contextUsage.memoryAll`):r(`contextUsage.memoryOff`);let o=C.activeCompaction,s;s=o&&n.compactionApplied?`
|
|
2127
2127
|
<div class="context-usage-compaction">
|
|
2128
|
-
<div class="context-usage-dim">${r(`contextUsage.compactionActive`,{count:o.compressedCount,tokens:
|
|
2128
|
+
<div class="context-usage-dim">${r(`contextUsage.compactionActive`,{count:o.compressedCount,tokens:F(o.summaryTokens)})}</div>
|
|
2129
2129
|
${tD()?`<button class="context-usage-btn primary" data-action="compact">${r(`contextUsage.btnCompactAgain`)}</button>`:`<button class="context-usage-btn danger-ghost" data-action="undo">${r(`contextUsage.btnUndoCompact`)}</button>`}
|
|
2130
2130
|
</div>`:n.compactionInvalid?`
|
|
2131
2131
|
<div class="context-usage-compaction">
|
|
@@ -2142,18 +2142,18 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2142
2142
|
<div class="context-usage-popup-body">
|
|
2143
2143
|
<div class="context-usage-total">
|
|
2144
2144
|
<span class="context-usage-total-percent">${i}%</span>
|
|
2145
|
-
<span class="context-usage-total-detail">${
|
|
2145
|
+
<span class="context-usage-total-detail">${dt(t.usedTokens)} / ${dt(t.contextWindow)}</span>
|
|
2146
2146
|
</div>
|
|
2147
2147
|
<div class="context-usage-bar"><div class="context-usage-bar-fill" style="width:${Math.min(i,100)}%"></div></div>
|
|
2148
2148
|
<div class="context-usage-section">
|
|
2149
|
-
<div class="context-usage-row"><span>${r(`contextUsage.rowSystem`)}</span><span>${
|
|
2150
|
-
<div class="context-usage-row"><span>${r(`contextUsage.rowTools`)}</span><span>${
|
|
2151
|
-
<div class="context-usage-row"><span>${r(`contextUsage.rowHistory`)}</span><span>${
|
|
2149
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowSystem`)}</span><span>${dt(n.system)}</span></div>
|
|
2150
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowTools`)}</span><span>${dt(n.tools)}</span></div>
|
|
2151
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowHistory`)}</span><span>${dt(n.history)}</span></div>
|
|
2152
2152
|
<div class="context-usage-dim">${c}</div>
|
|
2153
2153
|
${l}
|
|
2154
|
-
<div class="context-usage-row"><span>${r(`contextUsage.rowInput`)}</span><span>${
|
|
2154
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowInput`)}</span><span>${dt(n.input)}</span></div>
|
|
2155
2155
|
</div>
|
|
2156
|
-
<div class="context-usage-section context-usage-dim">${r(`contextUsage.refInfo`,{output:
|
|
2156
|
+
<div class="context-usage-section context-usage-dim">${r(`contextUsage.refInfo`,{output:dt(n.outputReserve),safety:dt(n.safetyMargin)})}</div>
|
|
2157
2157
|
<div class="context-usage-section">
|
|
2158
2158
|
<div class="context-usage-row"><span>${r(`contextUsage.memoryLabel`)}</span><span>${a}</span></div>
|
|
2159
2159
|
</div>
|
|
@@ -2170,4 +2170,4 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2170
2170
|
</div>
|
|
2171
2171
|
<div class="context-usage-summary-body"></div>
|
|
2172
2172
|
</div>
|
|
2173
|
-
`,document.body.appendChild(t);let n=t.querySelector(`.context-usage-summary-body`),i=t.querySelectorAll(`.context-usage-summary-tab`),a=t=>{i.forEach(e=>e.classList.toggle(`active`,e.dataset.mode===t)),t===`preview`?(n.classList.add(`markdown-body`),n.innerHTML=et(e.summary),
|
|
2173
|
+
`,document.body.appendChild(t);let n=t.querySelector(`.context-usage-summary-body`),i=t.querySelectorAll(`.context-usage-summary-tab`),a=t=>{i.forEach(e=>e.classList.toggle(`active`,e.dataset.mode===t)),t===`preview`?(n.classList.add(`markdown-body`),n.innerHTML=et(e.summary),rt()):(n.classList.remove(`markdown-body`),n.textContent=e.summary)};i.forEach(e=>e.addEventListener(`click`,()=>a(e.dataset.mode))),a(`preview`),t.querySelector(`.context-usage-summary-close`).addEventListener(`click`,()=>t.remove()),t.addEventListener(`click`,e=>{e.target===t&&t.remove()})}export{UC as $,Hc as $n,Ib as $t,aT as A,Df as An,ur as Ar,aS as At,Gw as B,md as Bn,wn as Br,ex as Bt,zT as C,Am as Cn,Yr as Cr,jS as Ct,Qw as D,rp as Dn,dr as Dr,QS as Dt,Xw as E,ap as En,hr as Er,JS as Et,Ew as F,xd as Fn,Er as Fr,sx as Ft,Kw as G,qu as Gn,nn as Gr,Sb as Gt,tw as H,Xd as Hn,mn as Hr,Vb as Ht,Iw as I,Yd as In,yr as Ir,nx as It,ZC as J,jl as Jn,kb as Jt,ww as K,au as Kn,Qt as Kr,Ob as Kt,Aw as L,Fd as Ln,br as Lr,Qb as Lt,Zw as M,ad as Mn,gr as Mr,Sx as Mt,eT as N,hd as Nn,pr as Nr,Bx as Nt,gT as O,$f as On,lr as Or,SC as Ot,rT as P,id as Pn,mr as Pr,xx as Pt,zw as Q,Xc as Qn,Hb as Qt,Nw as R,Nd as Rn,Tr as Rr,ax as Rt,MT as S,km as Sn,Zr as Sr,xC as St,qw as T,Rp as Tn,L as Tr,nC as Tt,qC as U,Sd as Un,cn as Ur,Kb as Ut,zC as V,pd as Vn,hn as Vr,fb as Vt,Tw as W,Hu as Wn,an as Wr,Cb as Wt,KC as X,Ol as Xn,Rb as Xt,Bw as Y,Dl as Yn,_b as Yt,Lw as Z,el as Zn,Ab as Zt,kT as _,Qm as _n,Ji as _r,IC as _t,JT as a,gy as an,po as ar,Cw as at,IT as b,Mm as bn,Qi as br,fC as bt,OT as c,jv as cn,zi as cr,CC as ct,GT as d,rh as dn,Ri as dr,MC as dt,zb as en,Tc as er,$C as et,jT as f,ih as fn,na as fr,LC as ft,UT as g,$m as gn,qi as gr,KS as gt,AT as h,th as hn,Zi as hr,GS as ht,KE as i,Nb as in,mo as ir,nw as it,oT as j,td as jn,or as jr,Dx as jt,iT as k,ip as kn,fr as kr,bS as kt,LT as l,Mv as ln,ta as lr,PC as lt,WT as m,nh as mn,Xi as mr,FC as mt,YE as n,hb as nn,Ys as nr,jw as nt,mE as o,Ah as on,qa as or,aC as ot,PT as p,oh as pn,Bi as pr,SS as pt,rw as q,Bu as qn,pb as qt,$E as r,yb as rn,xo as rr,GC as rt,VT as s,Zh as sn,ea as sr,lC as st,WE as t,Jb as tn,ac as tr,Sw as tt,CT as u,sh as un,Ki as ur,sC as ut,BT as v,zm as vn,$i as vr,cC as vt,TT as w,Bp as wn,oi as wr,eC as wt,xT as x,Dm as xn,$r as xr,DC as xt,DT as y,Bm as yn,Yi as yr,dC as yt,Fw as z,bd as zn,cr as zr,tx as zt};
|